Edytuj

Udostępnij za pośrednictwem


DateTime.CompareTo Method

Definition

Compares 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.

Overloads

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.

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.

Remarks

The two overloads of the CompareTo method return a signed number that indicates the relative value of this instance and the value argument, as shown in the following table.

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.

CompareTo(DateTime)

Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs

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.

public:
 virtual int CompareTo(DateTime value);
public int CompareTo (DateTime value);
abstract member CompareTo : DateTime -> int
override this.CompareTo : DateTime -> int
Public Function CompareTo (value As DateTime) As Integer

Parameters

value
DateTime

The object to compare to the current instance.

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.

Implements

Examples

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.

open System

type DateComparisonResult =
    | Earlier = -1
    | Later = 1
    | TheSame = 0

[<EntryPoint>]
let main _ =
    let thisDate = DateTime.Today

    // Define two DateTime objects for today's date next year and last year		
    // Call AddYears instance method to add/substract 1 year
    let thisDateNextYear = thisDate.AddYears 1
    let thisDateLastYear = thisDate.AddYears -1

    // Compare today to last year
    let comparison = thisDate.CompareTo thisDateLastYear |> enum<DateComparisonResult>
    printfn $"CompareTo method returns {int comparison}: {thisDate:d} is {comparison.ToString().ToLower()} than {thisDateLastYear:d}"

    // Compare today to next year
    let comparison = thisDate.CompareTo thisDateNextYear |> enum<DateComparisonResult>
    printfn $"CompareTo method returns {int comparison}: {thisDate:d} is {comparison.ToString().ToLower()} than {thisDateNextYear:d}"
                        
    0

// If run on December 31, 2021, the example produces the following output:
//    CompareTo method returns 1: 12/31/2021 is later than 12/31/2020
//    CompareTo method returns -1: 12/31/2021 is earlier than 12/31/2022
using System;

public class DateTimeComparison
{
   private enum DateComparisonResult
   {
      Earlier = -1,
      Later = 1,
      TheSame = 0
   };

   public static void Main()
   {
      DateTime thisDate = DateTime.Today;

      // Define two DateTime objects for today's date
      // next year and last year		
      DateTime thisDateNextYear, thisDateLastYear;

      // Call AddYears instance method to add/substract 1 year
      thisDateNextYear = thisDate.AddYears(1);
      thisDateLastYear = thisDate.AddYears(-1);

      // Compare dates
      //
      DateComparisonResult comparison;
      // Compare today to last year
      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);

      // Compare today to next year
      comparison = (DateComparisonResult) thisDate.CompareTo(thisDateNextYear);
      Console.WriteLine("CompareTo method returns {0}: {1:d} is {2} than {3:d}",
                        (int) comparison, thisDate, comparison.ToString().ToLower(),
                        thisDateNextYear);
   }
}
//
// If run on October 20, 2006, the example produces the following output:
//    CompareTo method returns 1: 10/20/2006 is later than 10/20/2005
//    CompareTo method returns -1: 10/20/2006 is earlier than 10/20/2007
Option Strict On

Module DateTimeComparison
   Private Enum DateComparisonResult
      Earlier = -1
      Later = 1
      TheSame = 0
   End Enum
   
   Public Sub Main()

      Dim thisDate As Date = Date.Today

      ' Define two DateTime objects for today's date 
      ' next year and last year		
      Dim thisDateNextYear, thisDateLastYear As Date

      ' Call AddYears instance method to add/substract 1 year
      thisDateNextYear = thisDate.AddYears(1)
      thisDateLastYear = thisDate.AddYears(-1)   

       
      ' Compare dates
      '
      Dim comparison As DateComparisonResult
      ' Compare today to last year
      comparison = CType(thisDate.CompareTo(thisDateLastYear), DateComparisonResult)
      Console.WriteLine("CompareTo method returns {0}: {1:d} is {2} than {3:d}", _ 
                        CInt(comparison), thisDate, comparison.ToString().ToLower(), _ 
                        thisDateLastYear)
      
      ' Compare today to next year
      comparison = CType(thisDate.CompareTo(thisDateNextYear), DateComparisonResult)
      Console.WriteLine("CompareTo method returns {0}: {1:d} is {2} than {3:d}", _
                        CInt(comparison), thisDate, comparison.ToString().ToLower(), _
                        thisDateNextYear)
   End Sub
End Module
'
' If run on October 20, 2006, the example produces the following output:
'    CompareTo method returns 1: 10/20/2006 is later than 10/20/2005
'    CompareTo method returns -1: 10/20/2006 is earlier than 10/20/2007

Remarks

To determine the relationship of the current instance to value, the CompareTo method compares the Ticks property of the current instance and value but ignores their Kind property. 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.

This method implements the System.IComparable<T> interface and performs slightly better than the DateTime.CompareTo(Object) method overload because it does not have to convert the value parameter to an object.

See also

Applies to

CompareTo(Object)

Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs

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.

public:
 virtual int CompareTo(System::Object ^ value);
public:
 int CompareTo(System::Object ^ value);
public int CompareTo (object? value);
public int CompareTo (object value);
abstract member CompareTo : obj -> int
override this.CompareTo : obj -> int
member this.CompareTo : obj -> int
Public Function CompareTo (value As Object) As Integer

Parameters

value
Object

A boxed object to compare, or null.

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.

Implements

Exceptions

value is not a DateTime.

Examples

The following example demonstrates the CompareTo method.

using namespace System;
void main()
{
   

   System::DateTime theDay(System::DateTime::Today.Year,7,28);
   int compareValue;
   try
   {
      compareValue = theDay.CompareTo( System::DateTime::Today );
   }
   catch ( ArgumentException^ ) 
   {
      System::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 );
   }
}
open System

let theDay = DateTime(DateTime.Today.Year, 7, 28)

try
    let compareValue = theDay.CompareTo DateTime.Today

    if compareValue < 0 then
        printfn $"{theDay:d} is in the past."
    elif compareValue = 0 then
        printfn $"{theDay:d} is today!"
    else // compareValue > 0
        printfn $"{theDay:d} has not come yet."
        
with :? ArgumentException ->
    Console.WriteLine("Value is not a DateTime");
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);
Dim thDay As New System.DateTime(System.DateTime.Today.Year, 7, 28)

Dim compareValue As Integer
Try
   compareValue = thDay.CompareTo(System.DateTime.Today)
Catch exp As ArgumentException
   System.Console.WriteLine("Value is not a DateTime")
End Try

If compareValue < 0 Then
   System.Console.WriteLine("{0:d} is in the past.", thDay)
ElseIf compareValue = 0 Then
   System.Console.WriteLine("{0:d} is today!", thDay)
Else   ' compareValue >= 1 
   System.Console.WriteLine("{0:d} has not come yet.", thDay)
End If

Remarks

To determine the relationship of the current instance to value, the CompareTo method compares the Ticks property of the current instance and value but ignores their Kind property. 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.

See also

Applies to