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;
LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));

前提

・Java 1.8以降

使うメリット

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

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

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

Java23_LocalDate.java
import java.time.LocalDate;

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

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

実行

java --enable-preview .\Java23_LocalDate.java

2024/09/28
2024/09/21

おまけ(SimpleDateFomatterの場合)

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

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

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

実行

java --enable-preview .\Java23_SimpleDateFomatter.java

2024/09/28
2024/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?