Compare two dates in C#
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.,
value < 0, if first date is earlier than the second date.value = 0, if first date is same as the second date.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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; public class Example { public static void Main() { var dt1 = DateTime.Today; var dt2 = DateTime.Today.AddDays(10); int result = DateTime.Compare(dt1, dt2); if (result < 0) { Console.WriteLine("First Date is earlier than the second date"); } else if (result > 0) { Console.WriteLine("First Date is later than the second date"); } else { Console.WriteLine("First Date is same as the second date"); } } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; public class Example { public static void Main() { DateTime dt1 = DateTime.Now; DateTime dt2 = DateTime.Now.AddDays(10); if (dt1.Date < dt2.Date) { Console.WriteLine("First Date is earlier than the second date"); } else if (dt1.Date > dt2.Date) { Console.WriteLine("First Date is later than the second date"); } else { Console.WriteLine("First Date is same as the second date"); } } } |
Output:
First Date is earlier than the second date
That's all about comparing two dates in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)