如何知道DateTime是否在C#中的DateRange之间

我需要知道Date是否在DateRange之间。我有三个日期:


// The date range

DateTime startDate;

DateTime endDate;


DateTime dateToCheck;

简单的解决方案是进行比较,但是有更聪明的方法吗?


提前致谢。


Smart猫小萌
浏览 767回答 3
3回答

慕哥9229398

不,做一个简单的比较对我来说很好看:return dateToCheck >= startDate && dateToCheck < endDate;值得考虑的事情:DateTime在时区方面有点奇怪。它可能是UTC,它可能是“本地的”,它可能是模棱两可的。确保你将苹果与苹果进行比较。考虑您的起点和终点应该是包容性的还是排他性的。我已经将上面的代码视为包含下限和独占上限。

ABOUTYOU

通常我会为这些事情创建Fowler's Range实现。public interface IRange<T>{&nbsp; &nbsp; T Start { get; }&nbsp; &nbsp; T End { get; }&nbsp; &nbsp; bool Includes(T value);&nbsp; &nbsp; bool Includes(IRange<T> range);}public class DateRange : IRange<DateTime>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; public DateRange(DateTime start, DateTime end)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Start = start;&nbsp; &nbsp; &nbsp; &nbsp; End = end;&nbsp; &nbsp; }&nbsp; &nbsp; public DateTime Start { get; private set; }&nbsp; &nbsp; public DateTime End { get; private set; }&nbsp; &nbsp; public bool Includes(DateTime value)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return (Start <= value) && (value <= End);&nbsp; &nbsp; }&nbsp; &nbsp; public bool Includes(IRange<DateTime> range)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return (Start <= range.Start) && (range.End <= End);&nbsp; &nbsp; }}用法非常简单:DateRange range = new DateRange(startDate, endDate);range.Includes(date)

慕尼黑的夜晚无繁华

您可以使用扩展方法使其更具可读性:public static class DateTimeExtensions{&nbsp; &nbsp; public static bool InRange(this DateTime dateToCheck, DateTime startDate, DateTime endDate)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return dateToCheck >= startDate && dateToCheck < endDate;&nbsp; &nbsp; }}现在你可以写:dateToCheck.InRange(startDate, endDate)
打开App,查看更多内容
随时随地看视频慕课网APP