DateTime.CompareTo メソッド

定義

このインスタンスの値と指定した DateTime の値を比較し、このインスタンスの値が指定した DateTime の値よりも前か、同じか、または後かを示します。

オーバーロード

CompareTo(DateTime)

このインスタンスの値と指定した DateTime の値を比較し、このインスタンスの値が指定した DateTime の値よりも前か、同じか、または後かを示す整数を返します。

CompareTo(Object)

このインスタンスの値と指定した DateTime の値を含む指定したオブジェクトを比較し、このインスタンスの値が指定した DateTime の値よりも前か、同じか、または後かを示す整数を返します。

注釈

メソッドの 2 つのオーバーロードは、次の CompareTo 表に示すように、このインスタンスと引数の相対値を value 示す符号付き数値を返します。

説明
0 より小さい値 このインスタンスは、value よりも前の日時です。
ゼロ このインスタンスは value と同じです。
0 より大きい値 このインスタンスは、value よりも後の日時です。

CompareTo(DateTime)

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

このインスタンスの値と指定した 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

現在のインスタンスと比較する対象のオブジェクト。

戻り値

このインスタンスと value パラメーターの相対値を示す符号付き数値。

説明
0 より小さい値 このインスタンスは、value よりも前の日時です。
ゼロ このインスタンスは value と同じです。
0 より大きい値 このインスタンスは、value よりも後の日時です。

実装

次の例では、3 つの DateTime オブジェクトをインスタンス化します。1 つは今日の日付を表し、もう 1 つは 1 年前の日付を表し、3 つ目は 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

注釈

現在のインスタンスと の関係を調べるには、 メソッドはCompareTo現在のインスタンスvalueの プロパティをTicks比較しますが、valueそのKindプロパティは無視します。 オブジェクトを比較する DateTime 前に、オブジェクトが同じタイム ゾーンの時刻を表していることを確認します。 これを行うには、プロパティの Kind 値を比較します。

このメソッドは インターフェイスを実装し、パラメーターを System.IComparable<T> オブジェクトに変換する必要がないため、メソッドのオーバーロードよりも DateTime.CompareTo(Object) 若干優れたパフォーマンスを value 発揮します。

こちらもご覧ください

適用対象

CompareTo(Object)

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

このインスタンスの値と指定した 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

比較対象のボックス化されたオブジェクト、または null

戻り値

このインスタンスと value の相対値を示す符号付き数値。

説明
0 より小さい値 このインスタンスは、value よりも前の日時です。
ゼロ このインスタンスは value と同じです。
0 より大きい値 このインスタンスは value より後の時刻を表しているか、または valuenull です。

実装

例外

valueDateTime ではありません。

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

注釈

現在のインスタンスと の関係を調べるには、 メソッドはCompareTo現在のインスタンスvalueの プロパティをTicks比較しますが、valueそのKindプロパティは無視します。 オブジェクトを比較する DateTime 前に、オブジェクトが同じタイム ゾーンの時刻を表していることを確認します。 これを行うには、プロパティの Kind 値を比較します。

のインスタンスは DateTime、その値に関係なく、 より null大きいと見なされます。

こちらもご覧ください

適用対象