「java」compareToメソッドでDate型の日付の前後を比較するサンプル

2021年1月15日

書式
日付A.compareTo(日付B)
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
import java.util.Date;
import java.util.GregorianCalendar;
public class CompareDate {
public static void main(String[] args) {
Date dtA = new GregorianCalendar(2021, 11, 20).getTime();
Date dtB = new GregorianCalendar(2021, 11, 22).getTime();
Date dtC = new GregorianCalendar(2019, 9, 22).getTime();
int resultA, resultB, resultC;
resultA = dtA.compareTo(dtB);
System.out.println("日付Aと日付Bの比較結果:" + resultA);
resultB = dtB.compareTo(dtC);
System.out.println("日付Aと日付Bの比較結果:" + resultB);
resultC = dtA.compareTo(dtC);
System.out.println("日付Aと日付Cの比較結果:" + resultC);
}
}
package com.arkgame.study; import java.util.Date; import java.util.GregorianCalendar; public class CompareDate { public static void main(String[] args) { Date dtA = new GregorianCalendar(2021, 11, 20).getTime(); Date dtB = new GregorianCalendar(2021, 11, 22).getTime(); Date dtC = new GregorianCalendar(2019, 9, 22).getTime(); int resultA, resultB, resultC; resultA = dtA.compareTo(dtB); System.out.println("日付Aと日付Bの比較結果:" + resultA); resultB = dtB.compareTo(dtC); System.out.println("日付Aと日付Bの比較結果:" + resultB); resultC = dtA.compareTo(dtC); System.out.println("日付Aと日付Cの比較結果:" + resultC); } }
package com.arkgame.study;

import java.util.Date;
import java.util.GregorianCalendar;

public class CompareDate {

      public static void main(String[] args) {
            Date dtA = new GregorianCalendar(2021, 11, 20).getTime();
            Date dtB = new GregorianCalendar(2021, 11, 22).getTime();
            Date dtC = new GregorianCalendar(2019, 9, 22).getTime();

            int resultA, resultB, resultC;
            resultA = dtA.compareTo(dtB);
            System.out.println("日付Aと日付Bの比較結果:" + resultA);

            resultB = dtB.compareTo(dtC);
            System.out.println("日付Aと日付Bの比較結果:" + resultB);

            resultC = dtA.compareTo(dtC);
            System.out.println("日付Aと日付Cの比較結果:" + resultC);

      }

}

実行結果
日付Aと日付Bの比較結果:-1
日付Aと日付Bの比較結果:1
日付Aと日付Cの比較結果:1

Java

Posted by arkgame