【发布时间】:2011-12-01 14:24:25
【问题描述】:
在 C# 中,我有 from 和 to DateTime 值,并想检查 value DateTime 是否在范围内,我该怎么做这个?
lowerBound = "01-Dec-2011 09:45:58"
upperBound = "01-Dec-2011 09:38:58"
value = "01-Dec-2011 09:49:58"
【问题讨论】:
在 C# 中,我有 from 和 to DateTime 值,并想检查 value DateTime 是否在范围内,我该怎么做这个?
lowerBound = "01-Dec-2011 09:45:58"
upperBound = "01-Dec-2011 09:38:58"
value = "01-Dec-2011 09:49:58"
【问题讨论】:
只需像处理数字一样使用比较运算符:
DateTime lowerBound = new DateTime(2011, 12, 1, 9, 38, 58);
DateTime upperBound = new DateTime(2011, 12, 1, 9, 49, 58);
DateTime value = new DateTime(2011, 12, 1, 9, 45, 58);
// This is an inclusive lower bound and an exclusive upper bound.
// Adjust to taste.
if (lowerBound <= value && value < upperBound)
您需要注意这些值都是相同的“种类”(UTC、本地、非特定)。如果您想及时比较瞬间,(例如“X 是否发生在 Y 之前”),最好使用 UTC。
【讨论】:
Between 函数?听起来更像 SQL 而不是 C#...