Search code examples
c#performancedatetimecomparison

DateTime compare (between) Date with day month year hours minutes and seconds


I would to check if a date fall between two limites.

StartDate = '2018-01-01 11:10:00' EndDate = '2018-02-01 14:00:30'

  1. CheckDate1 = '2018-01-01 11:09:00' -> FAIL
  2. CheckDate2 = '2018-01-01 11:10:01' -> OK
  3. CheckDate3 = '2018-01-01 14:00:31' -> FAIL
  4. CheckDate4 = '2018-01-01 14:00:29' -> OK

I tried the following check:

CheckDateX >= StartDate && CheckDateX <= EndDate;

This doesn't seems to take the seconds into account. So I tried the following check:

 CheckDateX.Ticks >= StartDate.Ticks  && CheckDateX.Ticks <= EndDate.Ticks;

But the result is also wrong. Is there a correct and elegant way to compare to DateTime in C#?


Solution

  • You should check that link : How to know if a DateTime is between a DateRange in C# People provided answers and even an extension for the same issue you are facing.