DateTime.CompareTo() Method in C#
Last Updated :
22 Jan, 2019
This method is used to compare the value of this instance to a specified DateTime value and indicates whether this instance is earlier than, the same as, or later than the specified DateTime value. There are two methods in the overload list of this method as follows:
- CompareTo(DateTime)
- CompareTo(Object)
CompareTo(DateTime) Method
This method is used to compare 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:
public int CompareTo (DateTime value);
Here, the parameter value is the object to compare to the current instance.
Return Value: This method return a signed number indicating the relative values of this instance and the value parameter.
- Less than zero : If this instance is earlier than value.
- Zero : If this instance is the same as value.
- Greater than zero : If this instance is later than value.
Example:
using System;
public class GFG {
public static void Main()
{
DateTime d1 = new DateTime(2018, 12,
31, 16, 0, 0);
DateTime d2 = new DateTime(2018, 12,
31, 20, 0, 0);
int res = d1.CompareTo(d2);
string r;
if (res > 0)
r = "is later than" ;
else if (res == 0)
r = "is the same time as" ;
else
r = "is earlier than" ;
Console.WriteLine( "{0} {1} {2}" , d1, r, d2);
}
}
|
Output:
12/31/2018 16:00:00 is earlier than 12/31/2018 20:00:00
CompareTo(Object) Method
This method is used to compare 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:
public int CompareTo (object value);
Here, the parameter value is the boxed object to compare, or null.
Return Value: This method return a signed number indicating the relative values of this instance and the value parameter.
- Less than zero : If this instance is earlier than value.
- Zero : If this instance is the same as value.
- Greater than zero : If this instance is later than value.
Exception: This method will give ArgumentException if the value is not a DateTime.
Example:
using System;
public class GFG {
public static void Main()
{
DateTime d1 = new DateTime(2018, 12,
31, 16, 0, 0);
int res = d1.CompareTo(DateTime.Today);
string r;
if (res > 0)
r = "is later than" ;
else if (res == 0)
r = "is the same time as" ;
else
r = "is earlier than" ;
Console.WriteLine( "{0} {1} {2}" , d1, r,
DateTime.Today);
}
}
|
Output:
12/31/2018 16:00:00 is earlier than 01/21/2019 00:00:00
Reference:
Share your thoughts in the comments
Please Login to comment...