locked
how to Compare Time Range RRS feed

  • Question

  • hi

      I have a time value which need to check whether this time value is in the time range or not.

     eg:  I need to check whether 09:00:00 lies in between 08:50:00 - 09:10:00 or not?

     how can I do this?

    thanks,
    hari
    Tuesday, April 14, 2009 5:44 AM

Answers

  • That is because the Dt.TimeOfDay is a TimeSpan property and StartTime is a DateTime Object . And you cant compare the two objects since they are different.

    Try the following code

    if

    (Dt.TimeOfDay> StartTime.TimeOfDay && Dt.TimeOfDay<EndTime.TimeOfDay)//Checking if the time is between start and end time

    MessageBox.Show("Time is in Range");

     

    else

    MessageBox.Show("time is not in range");


    Ganesh Ranganathan
    [Please mark the post as answer if you find it helpful]
    Tuesday, April 14, 2009 10:04 AM

All replies

  • Hi Haribabu,

    Please try the following code. You can use the greater than and less than operator with DateTime variables. You need to convert the time into a Datetime variable


    DateTime Dt = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,9,0,0);
    
    //The last three numbers are the Hours,minutes and seconds respectively
    DateTime StartTime = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,8,50,0);
    
    DateTime EndTime = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,9,10,0);
    
    if(Dt> StartTime && Dt<EndTime)//Checking if the time is between start and end time
            MessageBox.Show("Time is in Range");
    else
            MessageBox.Show("time is not in range");

    Ganesh Ranganathan
    [Please mark the post as answer if you find it helpful]
    Tuesday, April 14, 2009 6:18 AM
  • Hi Ganesh

       Its working fine thanks,

      one more doubt If I use
     
               if (Dt.TimeOfDay > StartTime && Dt.TimeOfDay < EndTime)
                    MessageBox.Show("Time is in Range");
                else
                    MessageBox.Show("time is not in range");

    its throwing following exception :
        "Operator '>' cannot be applied to operands of type 'System.TimeSpan' and 'System.DateTime'"  
    can u please clarify me.
    Tuesday, April 14, 2009 9:57 AM
  • That is because the Dt.TimeOfDay is a TimeSpan property and StartTime is a DateTime Object . And you cant compare the two objects since they are different.

    Try the following code

    if

    (Dt.TimeOfDay> StartTime.TimeOfDay && Dt.TimeOfDay<EndTime.TimeOfDay)//Checking if the time is between start and end time

    MessageBox.Show("Time is in Range");

     

    else

    MessageBox.Show("time is not in range");


    Ganesh Ranganathan
    [Please mark the post as answer if you find it helpful]
    Tuesday, April 14, 2009 10:04 AM
  • thanks for your reply Ganesh Its working.

    regards,
      hari
    Tuesday, April 14, 2009 10:07 AM