如何知道 C# 中的 DateTime 是否在 DateRange 之间
我需要知道日期是否在日期范围之间。我有三个日期:
// The date range
DateTime startDate;
DateTime endDate;
DateTime dateToCheck;
最简单的解决方案是进行比较,但是有没有更聪明的方法来做到这一点?
I need to know if a Date is between a DateRange. I have three dates:
// The date range
DateTime startDate;
DateTime endDate;
DateTime dateToCheck;
The easy solution is doing a comparison, but is there a smarter way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
不,做一个简单的比较对我来说看起来不错:
不过需要考虑的是:
DateTime
就时区而言是一种有点奇怪的类型。它可以是UTC,它可以是“本地”,它可以是不明确的。确保你是在将苹果与苹果进行比较。Nope, doing a simple comparison looks good to me:
Things to think about though:
DateTime
is a somewhat odd type in terms of time zones. It could be UTC, it could be "local", it could be ambiguous. Make sure you're comparing apples with apples, as it were.通常我会为此类事情创建 Fowler's Range 实现。
用法非常简单:
Usually I create Fowler's Range implementation for such things.
Usage is pretty simple:
您可以使用扩展方法使其更具可读性:
现在您可以编写:
You could use extension methods to make it a little more readable:
Now you can write:
您可以使用:
You can use:
我发现以下库在进行任何类型的日期数学计算时最有帮助。我仍然对 .Net 框架中没有这样的东西感到惊讶。
http://www.codeproject.com/Articles/168662/Time -NET 时期库
I’ve found the following library to be the most helpful when doing any kind of date math. I’m still amazed nothing like this is part of the .Net framework.
http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET
根据谢尔盖的答案,我认为这个更通用的版本更符合福勒的
范围
想法,并解决了该答案的一些问题,例如能够通过将T
约束为IComparable< 来在泛型类中拥有
Includes
方法/代码>。它也是不可变的,就像您所期望的扩展其他值类型(例如DateTime
)功能的类型一样。Following on from Sergey's answer, I think this more generic version is more in line with Fowler's
Range
idea, and resolves some of the issues with that answer such as being able to have theIncludes
methods within a generic class by constrainingT
asIComparable<T>
. It's also immutable like what you would expect with types that extend the functionality of other value types likeDateTime
.如果有人想要它作为验证器
用法
In case anyone wants it as a Validator
Usage