本文介绍了查找当前时间是否在时间范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 .NET 3.5

Using .NET 3.5

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

I want to determine if the current time falls in a time range.

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

So far I have the currentime:

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

我正在研究如何转换和比较时间范围.这行得通吗?

I'm blanking out on how to get the time range converted and compared.Would this work?

if (Convert.ToDateTime("11:59") <= currentTime.TimeOfDay
    && Convert.ToDateTime("13:01") >= currentTime.TimeOfDay)
{
   //match found
}

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

UPDATE1: Thanks everyone for your suggestions. I wasn't familiar with the TimeSpan function.

推荐答案

用于检查一天中的某个时间使用:

For checking for a time of day use:

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
}

这篇关于查找当前时间是否在时间范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 01:49
查看更多