[Java 8] Function that returns UTC time as Date type (calculated using OffsetZone)

In UTC time Even if I set the ZonedDateTime set to UTC to Date.from (***. ToInstant ()), it did not return the local time, so It's a story that I avoided it by getting Offset Zone from Offset Date Time and doing minus Seconds (shifting the time) while being sharp.

Code in question

example.java


ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("UTC")); 
Instant instant = zonedDateTime.toInstant();
return Date.fron(Instant);
//"Asisa/Tokyo"Time is coming back

↑ (I don't know, but it's because of the Java environment ... ??)

Resolved code

myexample.java



public static Date getUTCDate() {
    OffsetDateTime offsetDateTime = OffsetDateTime.now();
    //Here is Japan time (+9:00)
    OffsetZone offsetZone = offsetDateTime.getOffset();
    //(+9:00)Get
    OffsetDateTime UTCDateTime = offsetDateTime.minusSeconds(offsetZone.getTotalSeconds());
    //This is the UTC time.

    //Instantize and return with Date type Japan time(Date type)Is returned
    Instant instant = UTCDateTime.toInstant();
    return Date.from(instant);
}

I thought while I was investigating, but there are some Qiita articles that output UTC time in Java (without using LocalDateTime, ZonedDateTime), but most of them are returning in String type. ~~ Everyone dislikes Date type? ~~

Also, I learned anew this time that the Date type only holds the elapsed milliseconds since 1970/1/1 00:00:00. There is a lot of depth around the date ...

Recommended Posts

[Java 8] Function that returns UTC time as Date type (calculated using OffsetZone)
[Java] Date / time operations
[Java] Date type conversion