C# DateTime.Compare Method Guide
In C#, the DateTime.Compare() method is used to compare the values of two DateTime objects and returns an integer representing their relative order. The syntax of the method is as follows:
public static int Compare(DateTime t1, DateTime t2);
To use the DateTime.Compare() method, you just need to pass in the two DateTime objects that you want to compare as parameters and then retrieve the returned integer value. The meaning of the returned integer value is as follows:
- If t1 is less than t2, then return a negative integer.
- Return zero if t1 is equal to t2.
- If t1 is greater than t2, then return a positive integer.
Here is a sample code demonstrating how to use the DateTime.Compare() method:
DateTime date1 = new DateTime(2021, 1, 1);
DateTime date2 = new DateTime(2021, 1, 15);
int result = DateTime.Compare(date1, date2);
if (result < 0)
{
Console.WriteLine("日期1在日期2之前");
}
else if (result == 0)
{
Console.WriteLine("日期1等于日期2");
}
else
{
Console.WriteLine("日期1在日期2之后");
}
The comparison above shows the values of two DateTime objects, date1 and date2, and outputs corresponding information based on the comparison result.