How to compare DateTime in C#?
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!");
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
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
.