Find if current time falls in a time range
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
}
For absolute times use:
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
}
Some good answers here but none cover the case of your start time being in a different day than your end time. If you need to straddle the day boundary, then something like this may help:
TimeSpan start = TimeSpan.Parse("22:00"); // 10 PM
TimeSpan end = TimeSpan.Parse("02:00"); // 2 AM
TimeSpan now = DateTime.Now.TimeOfDay;
if (start <= end)
{
// start and stop times are in the same day
if (now >= start && now <= end)
{
// current time is between start and stop
}
}
else
{
// start and stop times are in different days
if (now >= start || now <= end)
{
// current time is between start and stop
}
}
Note that in this example the time boundaries are inclusive and that this still assumes less than a 24-hour difference between start
and stop
.
A simple little extension function for this:
public static bool IsBetween(this DateTime now, TimeSpan start, TimeSpan end)
{
var time = now.TimeOfDay;
// Scenario 1: If the start time and the end time are in the same day.
if (start <= end)
return time >= start && time <= end;
// Scenario 2: The start time and end time is on different days.
return time >= start || time <= end;
}
if (new TimeSpan(11,59,0) <= currentTime.TimeOfDay && new TimeSpan(13,01,0) >= currentTime.TimeOfDay)
{
//match found
}
if you really want to parse a string into a TimeSpan, then you can use:
TimeSpan start = TimeSpan.Parse("11:59");
TimeSpan end = TimeSpan.Parse("13:01");