DateTime.CompareTo 메서드

정의

이 인스턴스의 값을 지정된 DateTime 값과 비교하고 이 인스턴스가 지정된 DateTime 값보다 이전인지, 같은지 또는 이후인지를 나타냅니다.

오버로드

CompareTo(DateTime)

이 인스턴스의 값을 지정된 DateTime 값과 비교하고 이 인스턴스가 지정된 DateTime 값보다 이전인지, 같은지 또는 이후인지를 나타내는 정수를 반환합니다.

CompareTo(Object)

이 인스턴스의 값을 지정된 DateTime 값이 포함된 지정된 개체와 비교하고, 이 인스턴스가 지정된 DateTime 값보다 이전인지, 같은지 또는 이후인지를 나타내는 정수를 반환합니다.

설명

메서드의 CompareTo 두 오버로드는 다음 표와 같이 이 인스턴스의 상대 값과 인수를 value 나타내는 부호 있는 숫자를 반환합니다.

설명
0보다 작음 이 인스턴스는 value 보다 이전입니다.
0 이 인스턴스는 value와 같습니다.
0보다 큼 이 인스턴스는 value보다 이후입니다.

CompareTo(DateTime)

이 인스턴스의 값을 지정된 DateTime 값과 비교하고 이 인스턴스가 지정된 DateTime 값보다 이전인지, 같은지 또는 이후인지를 나타내는 정수를 반환합니다.

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

매개 변수

value
DateTime

현재 인스턴스와 비교할 개체입니다.

반환

Int32

이 인스턴스와 value 매개 변수의 상대 값을 나타내는 부호 있는 숫자입니다.

설명
0보다 작음 이 인스턴스는 value 보다 이전입니다.
0 이 인스턴스는 value와 같습니다.
0보다 큼 이 인스턴스는 value보다 이후입니다.

구현

예제

다음 예제에서는 3개의 DateTime 개체를 인스턴스화합니다. 하나는 오늘 날짜를 나타내고 다른 하나는 1년 전 날짜를 나타내는 개체이고, 세 번째 개체는 미래 날짜 1년을 나타냅니다. 그런 다음 메서드를 CompareTo(DateTime) 호출하고 비교 결과를 표시합니다.

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

설명

현재 인스턴스의 관계를 확인하기 위해 value메서드는 CompareTo 현재 인스턴스의 속성을 비교 Ticks 하지만 value 해당 Kind 속성을 무시합니다. 개체를 비교하기 DateTime 전에 개체가 동일한 표준 시간대의 시간을 나타내는지 확인합니다. 속성의 Kind 값을 비교하여 이 작업을 수행할 수 있습니다.

이 메서드는 인터페이스를 System.IComparable<T> 구현하고 매개 변수를 개체로 변환 value 할 필요가 없으므로 메서드 오버로드보다 DateTime.CompareTo(Object) 약간 더 잘 수행됩니다.

추가 정보

적용 대상

CompareTo(Object)

이 인스턴스의 값을 지정된 DateTime 값이 포함된 지정된 개체와 비교하고, 이 인스턴스가 지정된 DateTime 값보다 이전인지, 같은지 또는 이후인지를 나타내는 정수를 반환합니다.

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

매개 변수

value
Object

비교할 boxing된 개체이거나 null입니다.

반환

Int32

이 인스턴스와 value의 상대 값을 나타내는 부호 있는 숫자입니다.

설명
0보다 작음 이 인스턴스는 value 보다 이전입니다.
0 이 인스턴스는 value와 같습니다.
0보다 큼 이 인스턴스는 value보다 이후이거나 valuenull입니다.

구현

예외

value이(가) DateTime가 아닌 경우

예제

다음 예제는 CompareTo 메서드.

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

설명

현재 인스턴스의 관계를 확인하기 위해 value메서드는 CompareTo 현재 인스턴스의 속성을 비교 Ticks 하지만 value 해당 Kind 속성을 무시합니다. 개체를 비교하기 DateTime 전에 개체가 동일한 표준 시간대의 시간을 나타내는지 확인합니다. 속성의 Kind 값을 비교하여 이 작업을 수행할 수 있습니다.

값에 DateTime관계없이 모든 인스턴스는 보다 null큰 것으로 간주됩니다.

추가 정보

적용 대상