How to check if one DateTime is greater than the other in C#
I have two DateTime
objects: StartDate
and EndDate
. I want to make sure StartDate
is before EndDate
. How is this done in C#?
Solution 1:
if (StartDate < EndDate)
// code
if you just want the dates, and not the time
if (StartDate.Date < EndDate.Date)
// code
Solution 2:
if(StartDate < EndDate)
{}
DateTime supports normal comparision operators.
Solution 3:
You can use the overloaded < or > operators.
For example:
DateTime d1 = new DateTime(2008, 1, 1);
DateTime d2 = new DateTime(2008, 1, 2);
if (d1 < d2) { ...