John M John M - 1 month ago 11
C# Question

Find if current time falls in a time range

Using .NET 3.5

I want to determine if the current time falls in a time range.

So far I have the currentime:

DateTime currentTime = new DateTime();
currentTime.TimeOfDay;


I'm blanking out on how to get the time range converted and compared.
Would this work?

if (Convert.ToDateTime("11:59") <= currentTime.TimeOfDay
&& Convert.ToDateTime("13:01") >= currentTime.TimeOfDay)
{
//match found
}


UPDATE1: Thanks everyone for your suggestions. I wasn't familiar with the TimeSpan function.

Answer

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
}
Comments