Java 8: How to create a ZonedDateTime from an Epoch value?
Asked Answered
S

2

88

Java 8's LocalDateTime has an ofEpochSecond method. Unfortunately, there is no such method in the ZonedDateTime. Now, I have an Epoch value and an explicit ZoneId given. How do I get a ZonedDateTime out of these?

Sportsman answered 2/3, 2015 at 11:8 Comment(0)
B
152

You should be able to do this via the Instant class, which can represent a moment given the epoch time. If you have epoch seconds, you might create something via something like

Instant i = Instant.ofEpochSecond(t);
ZonedDateTime z = ZonedDateTime.ofInstant(i, zoneId);
Boldface answered 2/3, 2015 at 11:17 Comment(2)
ZonedDateTime.ofInstant(i, ZoneOffset.UTC) for UTCSystematology
Instant instant = Instant.ofEpochSecond(t); ZoneId zoneId = ZoneId.of("America/New_York"); ZonedDateTime z = ZonedDateTime.ofInstant(instant, zoneId); for a specific ZoneId.Hazel
L
3

Another simple way (different from that of the accepted answer) is to use Instant#atZone.

Demo:

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

public class Main {
    public static void main(String[] args) {
        // Sample Epoch seconds and ZoneId
        Instant instant = Instant.ofEpochSecond(1665256187);
        ZoneId zoneId = ZoneId.of("Europe/London");

        ZonedDateTime zdt = instant.atZone(zoneId);
        System.out.println(zdt);

        // Alternatively
        zdt = ZonedDateTime.ofInstant(instant, zoneId);
        System.out.println(zdt);
    }
}

Output:

2022-10-08T20:09:47+01:00[Europe/London]
2022-10-08T20:09:47+01:00[Europe/London]

Learn about the modern Date-Time API from Trail: Date Time.

Landloper answered 8/10, 2022 at 19:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.