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.
You can just use:
if (startTime < now && now < endTime)
Note that:
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;
}
See more on this question at Stackoverflow