「C#」CompareToで日付の前後判定を行うサンプル

2021年10月8日

書式
日付1.CompareTo(日付2)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public int CompareTo (DateTime value);
値         説明
0 より小さい値   このインスタンスは、value よりも前の日時です。
ゼロ         このインスタンスは value と同じです。
0            より大きい値このインスタンスは、value よりも後の日時です。
public int CompareTo (DateTime value); 値         説明 0 より小さい値   このインスタンスは、value よりも前の日時です。 ゼロ         このインスタンスは value と同じです。 0            より大きい値このインスタンスは、value よりも後の日時です。
public int CompareTo (DateTime value);
値	        説明
0 より小さい値	       このインスタンスは、value よりも前の日時です。
ゼロ	        このインスタンスは value と同じです。
0              より大きい値このインスタンスは、value よりも後の日時です。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
using System;
class Arkgame
{
public static void Main()
{
//DateTime型変数dtAの宣言
DateTime dtA = new DateTime(2021, 10, 8);
//DateTime型変数dtBの宣言
DateTime dtB = new DateTime(2021, 10, 9);
//DateTime型変数dtCの宣言
DateTime dtC = new DateTime(2021, 10, 7);
//現在の日付
DateTime today = DateTime.Today;
//現在日付と日付Aの前後判定
Console.WriteLine("結果1: " + today.CompareTo(dtA).ToString());
//現在日付と日付Bの前後判定
Console.WriteLine("結果2: " + today.CompareTo(dtB).ToString());
//現在日付と日付Cの前後判定
Console.WriteLine("結果3: " + today.CompareTo(dtC).ToString());
Console.ReadKey();
}
}
using System; class Arkgame { public static void Main() { //DateTime型変数dtAの宣言 DateTime dtA = new DateTime(2021, 10, 8); //DateTime型変数dtBの宣言 DateTime dtB = new DateTime(2021, 10, 9); //DateTime型変数dtCの宣言 DateTime dtC = new DateTime(2021, 10, 7); //現在の日付 DateTime today = DateTime.Today; //現在日付と日付Aの前後判定 Console.WriteLine("結果1: " + today.CompareTo(dtA).ToString()); //現在日付と日付Bの前後判定 Console.WriteLine("結果2: " + today.CompareTo(dtB).ToString()); //現在日付と日付Cの前後判定 Console.WriteLine("結果3: " + today.CompareTo(dtC).ToString()); Console.ReadKey(); } }
using System;
class Arkgame
{
    public static void Main()
    {
        //DateTime型変数dtAの宣言
        DateTime dtA = new DateTime(2021, 10, 8);
        //DateTime型変数dtBの宣言
        DateTime dtB = new DateTime(2021, 10, 9);
        //DateTime型変数dtCの宣言
        DateTime dtC = new DateTime(2021, 10, 7);

        //現在の日付
        DateTime today = DateTime.Today;

        //現在日付と日付Aの前後判定
        Console.WriteLine("結果1: " + today.CompareTo(dtA).ToString());
        //現在日付と日付Bの前後判定
        Console.WriteLine("結果2: " + today.CompareTo(dtB).ToString());
        //現在日付と日付Cの前後判定
        Console.WriteLine("結果3: " + today.CompareTo(dtC).ToString());
        
    
        Console.ReadKey();
    }
}

実行結果
結果1: 0
結果2: -1
結果3: 1

C#

Posted by arkgame