C# DateTime CompareTo(Object)

Description

DateTime CompareTo(Object) compares the value of this instance to a specified object that contains 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(Object) has the following syntax.


public int CompareTo(
  Object value
)

Parameters

DateTime.CompareTo(Object) has the following parameters.

  • value - A boxed object to compare, or null.

Returns

DateTime.CompareTo(Object) method returns A signed number indicating the relative values of this instance and value. 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, or value is null.

Example

The following example demonstrates the CompareTo method.


using System;// w w w. j  ava2 s .  c  om
public class MainClass{
  public static void Main(String[] argv){  
    System.DateTime theDay = new System.DateTime(System.DateTime.Today.Year, 7, 28);
    int compareValue;
    
    try {
        compareValue = theDay.CompareTo(DateTime.Today);
    } catch (ArgumentException) {
       Console.WriteLine("Value is not a DateTime");
       return;
    }
    
    if (compareValue < 0) 
       System.Console.WriteLine("{0:d} is in the past.", theDay);
    else if (compareValue == 0) 
       System.Console.WriteLine("{0:d} is today!", theDay);
    else // compareValue > 0
       System.Console.WriteLine("{0:d} has not come yet.", theDay);
  }
}
    

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