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

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?

47039 次浏览

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);

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.