「C#」CompareToで日付の前後判定を行うサンプル
書式
日付1.CompareTo(日付2)
public int CompareTo (DateTime value); 値 説明 0 より小さい値 このインスタンスは、value よりも前の日時です。 ゼロ このインスタンスは value と同じです。 0 より大きい値このインスタンスは、value よりも後の日時です。
使用例
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