Compare DateTime and returns an integer that indicates the sequence in CSharp
Description
The following code shows how to compare DateTime and returns an integer that indicates the sequence.
Example
//from ww w.ja v a2 s.c om
using System;
public class DateTimeComparison
{
private enum DateComparisonResult
{
Earlier = -1,
Later = 1,
TheSame = 0
};
public static void Main()
{
DateTime thisDate = DateTime.Today;
DateTime thisDateNextYear, thisDateLastYear;
// Call AddYears instance method to add/substract 1 year
thisDateNextYear = thisDate.AddYears(1);
thisDateLastYear = thisDate.AddYears(-1);
// Compare dates
DateComparisonResult comparison;
comparison = (DateComparisonResult) thisDate.CompareTo(thisDateLastYear);
Console.WriteLine("CompareTo method returns {0}: {1:d} is {2} than {3:d}",
(int) comparison, thisDate, comparison.ToString().ToLower(),
thisDateLastYear);
}
}
The code above generates the following result.