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からの経過ミリ秒を保持してるだけっていうのを今回新しく知りました。
日付周りは奥が深いっスね...