How to compare DateTime in C#?
In general case you need to compare DateTimes
with the same Kind
:
if (date1.ToUniversalTime() < date2.ToUniversalTime())
Console.WriteLine("date1 is earlier than date2");
Explanation from MSDN about DateTime.Compare
(This is also relevant for operators like >
, <
, ==
and etc.):
To determine the relationship of t1 to t2, the Compare method compares the Ticks property of t1 and t2 but ignores their Kind property. Before comparing DateTime objects, ensure that the objects represent times in the same time zone.
Thus, a simple comparison may give an unexpected result when dealing with DateTimes
that are represented in different timezones.
Microsoft has also implemented the operators '<' and '>'. So you use these to compare two dates.
if (date1 < DateTime.Now)
Console.WriteLine("Less than the current time!");
MuSTaNG's answer says it all, but I am still adding it to make it a little more elaborate, with links and all.
The conventional operators
- greater than (
>
), - less than (
<
), - equality (
==
), - and more
are available for DateTime
since .NET Framework 1.1. Also, addition and subtraction of DateTime
objects are also possible using conventional operators +
and -
.
One example from MSDN:
Equality:System.DateTime april19 = new DateTime(2001, 4, 19);
System.DateTime otherDate = new DateTime(1991, 6, 5);
// areEqual gets false.
bool areEqual = april19 == otherDate;
otherDate = new DateTime(2001, 4, 19);
// areEqual gets true.
areEqual = april19 == otherDate;
Other operators can be used likewise.
Here is the list all operators available for DateTime
.
MSDN: DateTime.Compare
DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;
if (result < 0)
relationship = "is earlier than";
else if (result == 0)
relationship = "is the same time as";
else
relationship = "is later than";
Console.WriteLine("{0} {1} {2}", date1, relationship, date2);
// The example displays the following output:
// 8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 PM