简体   繁体   English

如何知道当前时间是否介于两个时间段之间?

[英]How to know if current time is between two timespans?

I have two time spans like so: 我有两个这样的时间跨度:

TimeSpan Starttime : 16:37:00
TimeSpan EndTime: 17:37:00

current time: 当前时间:

DateTime currentDate = DateTime.Now;
TimeSpan now = currentDate.TimeOfDay;

Problem : 问题

I can't figure out how to know if the current time is between starttime and endtime. 我无法弄清楚如何知道当前时间是否在开始时间和结束时间之间。 i want to send mesages only between those two timespans. 我想只在这两个时间盘之间发送消息。

How do i do this? 我该怎么做呢?

My attempt: 我的尝试:

 if(startTime.Hours < now.Hours && endTime.Hours > now.Hours)
   // do stuff

This does not cover all scenarios since I need it to be exactly between starttime and endtime to the last second but I dont know how to do this. 这并不涵盖所有场景,因为我需要它恰好在starttime和endtime之间到最后一秒,但我不知道如何做到这一点。

You can just use: 你可以使用:

if (startTime < now && now < endTime)

Note that: 注意:

  • This doesn't check the date; 这不会检查日期; doesn't look like that's an issue here 这看起来不像是一个问题
  • Depending on why you're doing this, you may want to consider intervals such as "10pm-2am" at which point you effectively want to reverse the logic 根据您这样做的原因,您可能需要考虑诸如“10 pm-2am”之间的时间间隔,此时您实际上想要反转逻辑
  • In most cases, it's worth making the lower-bound inclusive and the upper-bound exclusive, eg 在大多数情况下,值得制定下限包含和上限独占,例如

     if (startTime <= now && now < endTime) 

    That's useful because then you can have several intervals where the end of one interval is the start of the next interval, and any one time is in exactly one interval. 这很有用,因为那时你可以有几个间隔,其中一个间隔的结束是下一个间隔的开始,任何一个时间恰好是一个间隔。

To handle the "10pm-2am" example, you'd want something like: 要处理“10 pm-2am”示例,您需要以下内容:

if (interval.StartTime < interval.EndTime)
{
    // Normal case, e.g. 8am-2pm
    return interval.StartTime <= candidateTime && candidateTime < interval.EndTime;
}
else
{
    // Reverse case, e.g. 10pm-2am
    return interval.StartTime <= candidateTime || candidateTime < interval.EndTime;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM