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?

【備忘録】Java言語で日付(yyyy/MM/dd)を最速で取得する

Last updated at Posted at 2024-09-28

結論

import java.time.LocalDate;
String todayString = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));

前提

・Java 1.8以降

使うメリット

SimpleDateFormatを使う場合に比べ、ちょっとコードが短い

日付を加算・減算したい場合においては、SimpleDateFormatを使う場合に比べ、遥かにコードが短い

ソースコード(Java 25を体験したかったので、Java 25用のコードです)

Java25_LocalDate.java
import java.time.LocalDate;

void main() {
    // 現在日を出力
    IO.println(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")));

    // 7日前を出力
    IO.println(LocalDate.now().minusDays(7).format(DateTimeFormatter.ofPattern("yyyy/MM/dd")));
}

実行

java --enable-preview .\Java25_LocalDate.java

2025/09/28
2025/09/21


おまけ(SimpleDateFomatterの場合)

Java25_SimpleDateFomatter.java
import java.time.format.DateTimeFormatter;
import java.util.Calendar;

void main() {
    // 現在日を出力
    IO.println(new SimpleDateFormat("yyyy/MM/dd").format(Calendar.getInstance().getTime()));

    // 7日前を出力
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_MONTH, -7);
    IO.println(new SimpleDateFormat("yyyy/MM/dd").format(calendar.getTime()));
}

実行

java --enable-preview .\Java25_SimpleDateFomatter.java

2025/09/28
2025/09/21

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?