0
1

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 で現在の日本標準時(JST)を取得する方法

Posted at

Java の java.time パッケージを使って、日本標準時(JST, UTC+9)を取得する方法を紹介します。

1. LocalDateTime.now() の問題点

通常、LocalDateTime.now() を使うと、システムのデフォルトタイムゾーンの現在時刻が取得されます。
しかし、サーバーのタイムゾーンが UTC になっている場合、日本時間ではなく UTC の時間が取得されてしまいます。

import java.time.LocalDateTime;

public class Main {
    public static void main(String[] args) {
        System.out.println(LocalDateTime.now()); // システムのタイムゾーンの現在時刻
    }
}

この場合、日本時間とは異なる可能性があるため、明示的に JST(日本標準時)を指定する必要があります。

2. ZonedDateTime を使って JST を取得する

Java では ZoneId.of("Asia/Tokyo") を指定することで、日本時間の現在時刻を取得できます。

import java.time.ZonedDateTime;
import java.time.ZoneId;

public class Main {
    public static void main(String[] args) {
        ZonedDateTime jstNow = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));
        System.out.println(jstNow); // JST の現在時刻
    }
}

jshell を使う場合は、次のコマンドを実行するだけで OK です。

java.time.ZonedDateTime.now(java.time.ZoneId.of("Asia/Tokyo"))

3. Instant から JST に変換する

もし UTC の Instant を JST に変換したい場合は、以下のように ZonedDateTime に変換できます。

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Main {
    public static void main(String[] args) {
        Instant now = Instant.now(); // UTC の現在時刻
        ZonedDateTime jstTime = now.atZone(ZoneId.of("Asia/Tokyo"));
        System.out.println(jstTime); // JST の現在時刻
    }
}

まとめ

  • LocalDateTime.now() はシステムのデフォルトタイムゾーンに依存するため、日本時間を取得するとは限らない
  • ZonedDateTime.now(ZoneId.of("Asia/Tokyo")) を使うと、日本時間(JST)を確実に取得できる
  • UTC の Instant から JST に変換するには Instant.now().atZone(ZoneId.of("Asia/Tokyo")) を使う
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?