This post will discuss how to compare two dates in C#.

1. Using DateTime.Compare() method

The DateTime.Compare() method is commonly used in C# to compare two instances of DateTime object. It returns an integer value based on the comparison result – indicating whether the first date is earlier than, the same as, or later than the second date. i.e.,

  1. value < 0, if first date is earlier than the second date.
  2. value = 0, if first date is same as the second date.
  3. value > 0, if first date is later than the second date.

The following example illustrates the usage of the DateTime.Compare() method for the comparison of two DateTime objects.

Download  Run Code

Output:

First Date is earlier than the second date

2. Using Relational Operators

Alternatively, you can use the relational operators – <, '<', <=, '<=', '==', '=!', etc. to compare two DateTime instances in C#. The following example provides an illustration.

Download  Run Code

Output:

First Date is earlier than the second date

That's all about comparing two dates in C#.