我需要知道一个日期是否在日期范围内。我有三个日期:
// The date range
DateTime startDate;
DateTime endDate;
DateTime dateToCheck;
简单的解决方法是进行比较,但有没有更聪明的方法来做到这一点?
我需要知道一个日期是否在日期范围内。我有三个日期:
// The date range
DateTime startDate;
DateTime endDate;
DateTime dateToCheck;
简单的解决方法是进行比较,但有没有更聪明的方法来做到这一点?
不,对我来说进行简单的比较看起来不错:
return dateToCheck >= startDate && dateToCheck < endDate;
不过需要考虑以下几点:
DateTime
类型在时区方面有些奇怪。它可能是 UTC 时间,也可能是“本地”时间,还可能是模棱两可的时间。确保比较的是同一种类型的时间。DateTime
是相同类型(UTC/本地时间)很重要。如果类型不同,则会比较原始时间而不是将两者转换为公共类型。 - CodesInChaosreturn startDate <= dateToCheck && dateToCheck < endDate
看起来更易读。 - Mauricio MoralesdateToCheck
是被检查的对象,我会像@JonSkeet那样首先写它(在&&
的两侧)。 - Zero3public interface IRange<T>
{
T Start { get; }
T End { get; }
bool Includes(T value);
bool Includes(IRange<T> range);
}
public class DateRange : IRange<DateTime>
{
public DateRange(DateTime start, DateTime end)
{
Start = start;
End = end;
}
public DateTime Start { get; private set; }
public DateTime End { get; private set; }
public bool Includes(DateTime value)
{
return (Start <= value) && (value <= End);
}
public bool Includes(IRange<DateTime> range)
{
return (Start <= range.Start) && (range.End <= End);
}
}
使用方法非常简单:
DateRange range = new DateRange(startDate, endDate);
range.Includes(date)
您可以使用扩展方法使代码更易读:
public static class DateTimeExtensions
{
public static bool InRange(this DateTime dateToCheck, DateTime startDate, DateTime endDate)
{
return dateToCheck >= startDate && dateToCheck < endDate;
}
}
现在,您可以编写:
dateToCheck.InRange(startDate, endDate)
您可以使用:
return (dateTocheck >= startDate && dateToCheck <= endDate);
Range
概念,并解决了该答案的一些问题,例如通过将 T
约束为 IComparable<T>
以在通用类中使用 Includes
方法。它也像扩展其他值类型功能的类型(如 DateTime
)一样是不可变的。public struct Range<T> where T : IComparable<T>
{
public Range(T start, T end)
{
Start = start;
End = end;
}
public T Start { get; }
public T End { get; }
public bool Includes(T value) => Start.CompareTo(value) <= 0 && End.CompareTo(value) >= 0;
public bool Includes(Range<T> range) => Start.CompareTo(range.Start) <= 0 && End.CompareTo(range.End) >= 0;
}
如果有人想要它作为验证器
using System;
using System.ComponentModel.DataAnnotations;
namespace GROOT.Data.Validation;
internal class DateRangeAttribute : ValidationAttribute
{
public string EndDate;
public string StartDate;
public override bool IsValid(object value)
{
return (DateTime)value >= DateTime.Parse(StartDate) && (DateTime)value <= DateTime.Parse(EndDate);
}
}
用法
[DateRange(
StartDate = "01/01/2020",
EndDate = "01/01/9999",
ErrorMessage = "Property is outside of range")
]