0
0

More than 3 years have passed since last update.

【Java8】UTC時刻をDate型で返す関数(OffsetZoneを用いて計算)

Posted at

UTC時刻で
UTCに設定したZonedDateTimeをDate.from(***.toInstant())しても現地時間しかしか返してくれなかったので、
なんでやねんとキレながらOffsetDateTimeからOffsetZone取得してminusSeconds(時間をずらす)することで回避したよという話。

問題のコード
example.java
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("UTC")); 
Instant instant = zonedDateTime.toInstant();
return Date.fron(Instant);
//"Asisa/Tokyo"時間が返ってくる なんでやねん

↑(よくわからんけどJavaの環境のせい...??)

解決したコード
myexample.java

public static Date getUTCDate() {
    OffsetDateTime offsetDateTime = OffsetDateTime.now();
    //ここでは日本時間(+9:00)
    OffsetZone offsetZone = offsetDateTime.getOffset();
    //(+9:00)を取得
    OffsetDateTime UTCDateTime = offsetDateTime.minusSeconds(offsetZone.getTotalSeconds());
    //これでUTC時刻になる。

    //Instant化してDate型でreturn 日本時間(Date型)が返ってくる
    Instant instant = UTCDateTime.toInstant();
    return Date.from(instant);
}

調べてる最中に思ったんですけど、(LocalDateTime,ZonedDateTime使わずに)JavaでUTC時刻を出すQiita記事そこそこあるけど、そのほとんどがString型でreturnしている。 みんなDate型きらいなん?

あとDate型って1970/1/1 00:00:00からの経過ミリ秒を保持してるだけっていうのを今回新しく知りました。
日付周りは奥が深いっスね...

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