0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Java】DateクラスのcompareToメソッドの使い方

Posted at

#compareToメソッドとは?
Dateクラスの日にちを比較するメソッドで、メソッドの呼び出し元の日付と引数の日付を比較します。

以下のように、引数と呼び出し元を比較し、値を返します

メソッドの呼び出し元の値が、引数と等しい場合は0
メソッドの呼び出し元の値が、引数より前の場合は-1
メソッドの呼び出し元の値が、引数より後の場合は1

#使い方

        SimpleDateFormat sdf  = new SimpleDateFormat("yyyyMMdd");
		Date date1,date2;
        date1 = sdf.parse("20210117");
	    date2 = sdf.parse("20210118");

        System.out.println(date1.compareTo(date2)); // -1 ->date1はdate2より前である
        System.out.println(date2.compareTo(date1)); // 1 ->date2はdate1より後である

#参照
クラス Date #compareTo

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?