Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to know if a Date is between a DateRange. I have three dates:

// The date range DateTime startDate; DateTime endDate;  DateTime dateToCheck; 

The easy solution is doing a comparison, but is there a smarter way to do this?

like image 538
Daniel Peñalba Avatar asked Jan 24 '11 11:01

Daniel Peñalba


People also ask

How do you know if a date is overlapping?

You can do this by swapping the ranges if necessary up front. Then, you can detect overlap if the second range start is: less than or equal to the first range end (if ranges are inclusive, containing both the start and end times); or. less than (if ranges are inclusive of start and exclusive of end).


1 Answers

Nope, doing a simple comparison looks good to me:

return dateToCheck >= startDate && dateToCheck < endDate; 

Things to think about though:

  • DateTime is a somewhat odd type in terms of time zones. It could be UTC, it could be "local", it could be ambiguous. Make sure you're comparing apples with apples, as it were.
  • Consider whether your start and end points should be inclusive or exclusive. I've made the code above treat it as an inclusive lower bound and an exclusive upper bound.
like image 68
Jon Skeet Avatar answered Sep 23 '22 16:09

Jon Skeet