0

I need to compare that the current time is within a specific range. I've tried the following

DateTime currentTime = DateTime.Now; 
int Comaprestart = DateTime.Compare(currentTime, startTime);
int CompareEnd = DateTime.Compare(currentTime,endTime);
if ((Comaprestart >= 0) && (CompareEnd <= 0))
     LinkBtnQuiz.Enabled = true;

It doesn't work right. for example I have the end time equal '2014-06-08 13:30:00.000' and the current time equal '2014-06-08 13:12:00.000' but I get CompareEnd=1 while it should be -1 as the current time is earlier than the end time.

Any idea of what is causing the error??

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Heba
  • 1
  • 1
  • 5
    `if (startTime < currentTime && currentTime < endTime)` – Matt Burland Aug 06 '14 at 03:33
  • @MattBurland Still not working. The problem seems in comparing the current time with the end time! I have endTime = '2014-06-08 14:30:00.000' and currentTime = '2014-06-08 14:25:00.000' – Heba Aug 06 '14 at 04:26
  • @MattBurland Do you think that it matters if the system read the date time in 12 hours format? My system time is in 12 hors format – Heba Aug 06 '14 at 05:06
  • No. Date comparisions in the .NET framework work. It would be a pretty big deal if they didn't. Are you sure what you think the times are in those `DateTime` objects are correct? How do you populate them in the first place? Look [here](https://dotnetfiddle.net/eKjruG). It works just fine. Are you sure your `DateTime` are all in the same time zone? – Matt Burland Aug 06 '14 at 12:37
  • You're right. the Problem was in the format. – Heba Aug 19 '14 at 01:36

2 Answers2

1

you can do it easier:

if(currentTime >= startTime && currentTime <= endTime)
{
   LinkBtnQuiz.Enabled = true;
}
Dmitry Khryukin
  • 6,408
  • 7
  • 36
  • 58
0
return dateToCheck >= startDate && dateToCheck < endDate;

Check this answer How to know if a DateTime is between a DateRange in C#

Community
  • 1
  • 1
Nayana Adassuriya
  • 23,596
  • 30
  • 104
  • 147