如何知道一个DateTime是DATERANGE之间在C#DateTime、DATERANGE

2023-09-02 10:24:33 作者:穿著校服去相親

我需要知道,如果日期是DATERANGE之间。我有三个日期:

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?

在此先感谢。

推荐答案

不,做一个简单的比较,对我来说很好:

Nope, doing a simple comparison looks good to me:

return dateToCheck >= startDate && dateToCheck < endDate;

事情要考虑,虽然:

Things to think about though:

的DateTime 是一个有些奇怪的类型时区的条款。这可能是UTC,也可能是本地,也可能是不明确的。确保你比较苹果与苹果,因为它是。 在考虑你的起点和终点是否应包括或不包括。我做了code以上将其作为一个包容性的下界和上界。 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. Consider whether your start and end points should be inclusive or exclusive. I've made the code above treat it as an inclusive lower bound and an exclusive upper bound.