使用 .NET 3.5

我想确定当前时间是否在一个时间范围内。

到目前为止,我有当前时间:

DateTime currentTime = new DateTime();
currentTime.TimeOfDay;

我正在研究如何转换和比较时间范围。
这行得通吗?
if (Convert.ToDateTime("11:59") <= currentTime.TimeOfDay
    && Convert.ToDateTime("13:01") >= currentTime.TimeOfDay)
{
   //match found
}

UPDATE1:感谢大家的建议。我不熟悉 TimeSpan 函数。

最佳答案

要检查一天中的某个时间,请使用:

TimeSpan start = new TimeSpan(10, 0, 0); //10 o'clock
TimeSpan end = new TimeSpan(12, 0, 0); //12 o'clock
TimeSpan now = DateTime.Now.TimeOfDay;

if ((now > start) && (now < end))
{
   //match found
}

对于绝对时间使用:
DateTime start = new DateTime(2009, 12, 9, 10, 0, 0)); //10 o'clock
DateTime end = new DateTime(2009, 12, 10, 12, 0, 0)); //12 o'clock
DateTime now = DateTime.Now;

if ((now > start) && (now < end))
{
   //match found
}

关于c# - 查找当前时间是否在时间范围内,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1504494/

10-17 01:57