Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 297
ThunD3eR Avatar asked Dec 04 '22 00:12

ThunD3eR


1 Answers

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
  • In most cases, it's worth making the lower-bound inclusive and the upper-bound exclusive, e.g.

    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:

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;
}
like image 127
Jon Skeet Avatar answered Dec 18 '22 05:12

Jon Skeet