如何检查C#DateTime是否在一个范围内

sha*_*mim 0 c# datetime

在C#中我日期时间瓦莱斯并要检查是否的DateTime在此范围内,我该怎么办呢?

lowerBound = "01-Dec-2011 09:45:58"
upperBound = "01-Dec-2011 09:38:58"
value = "01-Dec-2011 09:49:58"
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

只需使用比较运算符,就像使用数字一样:

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)
Run Code Online (Sandbox Code Playgroud)

您需要注意的是,这些值都是相同的"种类"(UTC,本地,非特定).如果你想及时比较时刻,(例如"在Y之前发生X"),最好使用UTC.

  • @SreenathPlakkat:你指的是哪个`Between`功能?听起来更像是SQL而不是C#...... (3认同)