CompareTo Method (Object)
Collapse the table of content
Expand the table of content

DateTime.CompareTo Method (Object)

[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]

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.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

public int CompareTo(
	Object value


Type: System.Object
The object to compare to this instance, or null.

Return Value

Type: System.Int32
A signed integer that indicates the relationship between this instance and the value parameter, as shown in the following table.



Less than zero

This instance is earlier than value.


This instance is the same as value.

Greater than zero

This instance is later than value, or value is null.




value is not a DateTime.

Before comparing DateTime objects, make sure that the objects represent times in the same time zone. You can do this by comparing the values of their Kind properties.

Any instance of DateTime, regardless of its value, is considered greater than null.

The following example demonstrates the CompareTo method.

System.DateTime theDay = new System.DateTime(System.DateTime.Today.Year, 7, 28);
int compareValue;

   compareValue = theDay.CompareTo(DateTime.Today);
catch (ArgumentException)
   outputBlock.Text += "Value is not a DateTime" + "\n";

if (compareValue < 0)
   outputBlock.Text += String.Format("{0:d} is in the past.", theDay) + "\n";
else if (compareValue == 0)
   outputBlock.Text += String.Format("{0:d} is today!", theDay) + "\n";
else // compareValue > 0
   outputBlock.Text += String.Format("{0:d} has not come yet.", theDay) + "\n";

Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Windows Phone

© 2017 Microsoft