C# DateTime CompareTo(DateTime)

Description

DateTime CompareTo(DateTime) compares the value of this instance to a specified DateTime value and returns an integer that indicates whether this instance is earlier than, the same as, or later than the specified DateTime value.

Syntax

DateTime.CompareTo(DateTime) has the following syntax.


public int CompareTo(
  DateTime value
)

Parameters

DateTime.CompareTo(DateTime) has the following parameters.

  • value - The object to compare to the current instance.

Returns

DateTime.CompareTo(DateTime) method returns A signed number indicating the relative values of this instance and the value parameter. Value Description Less than zero This instance is earlier than value. Zero This instance is the same as value. Greater than zero This instance is later than value.

Example

The following example instantiates three DateTime objects, one that represents today's date, another that represents the date one year previously, and a third that represents the date one year in the future. It then calls the CompareTo(DateTime) method and displays the result of the comparison.


/*from   www .  ja  v  a  2  s .co m*/

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.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version