使用.NET 3.5
我想确定当前时间是否在某个时间范围内。
到目前为止,我有currentime:
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 }