1
2

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 1 year has passed since last update.

JavaでString型の日付や日時の比較をする

Posted at

JavaでString型の日付や日時の比較をする

例えば以下のような2つのString型で表された日付を考える

String date1 = "2022-1-1";
String date2 = "2022-1-5";

String型の日付の比較

①SimpleDateFormatのオブジェクトを生成

SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd");

②比較する

// date1がdate2よりまえの場合
sdFormat.parse(date1).compareTo(sdFormat.parse(date2)) == -1

// date1がdate2よりあとの場合
sdFormat.parse(date1).compareTo(sdFormat.parse(date2)) == 1

// date1がdate2と同じ日の場合
sdFormat.parse(date1).compareTo(sdFormat.parse(date2)) == 0

String型の日時の比較

①SimpleDateFormatのオブジェクトを生成

SimpleDateFormat sdFormatDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

②比較する

// date1がdate2よりまえの場合
sdFormat.parse(date1).compareTo(sdFormat.parse(date2)) == -1

// date1がdate2よりあとの場合
sdFormat.parse(date1).compareTo(sdFormat.parse(date2)) == 1

// date1がdate2と同じ日の場合
sdFormat.parse(date1).compareTo(sdFormat.parse(date2)) == 0
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?