Find if current time falls in a time range

Viewed 202460

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.

12 Answers

Will this be simpler for handling the day boundary case? :)

TimeSpan start = TimeSpan.Parse("22:00");  // 10 PM
TimeSpan end = TimeSpan.Parse("02:00");    // 2 AM
TimeSpan now = DateTime.Now.TimeOfDay;

bool bMatched = now.TimeOfDay >= start.TimeOfDay &&
                now.TimeOfDay < end.TimeOfDay;
// Handle the boundary case of switching the day across mid-night
if (end < start)
    bMatched = !bMatched;

if(bMatched)
{
    // match found, current time is between start and end
}
else
{
    // otherwise ... 
}

We didn't want our service to run during the night. So we created this condition to check that current time in within the time window of 9am (today) and 1am (the next day):

if (DateTime.Now > DateTime.Now.Date && DateTime.Now <= DateTime.Now.Date.AddHours(1.00) || 
DateTime.Now >= DateTime.Now.Date.AddHours(9))
{
 // Current Time is within specified time window.
}

4 times checking

public static void GetTime()
        {
            var dt =  DateTime.Now;
            int hours = dt.Hour;
            int min = dt.Minute;

            if (hours >= 1 && hours <= 12)
            {
                //Good Morning
            }
            else if (hours >= 12 && hours <= 16)
            {
                //Good Afternoon
            }
            else if (hours >= 16 && hours <= 21)
            {
                //Good Evening
            }
            else if (hours >= 21 && hours <= 24)
            {
                //Good Night
            }
        }
 using System;

 public class Program
 {
    public static void Main()
    {
        TimeSpan t=new TimeSpan(20,00,00);//Time to check

        TimeSpan start = new TimeSpan(20, 0, 0); //8 o'clock evening

        TimeSpan end = new TimeSpan(08, 0, 0); //8 o'clock Morning

        if ((start>=end && (t<end ||t>=start))||(start<end && (t>=start && t<end)))
        {
           Console.WriteLine("Mached");
        }
        else
        {
            Console.WriteLine("Not Mached");
        }

    }
 }
Related