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?
Asked
Active
Viewed 5.2k times
2 Answers
149
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);
-
53`ZonedDateTime.ofInstant(i, ZoneOffset.UTC)` for UTC – Ilya Serbis Oct 27 '17 at 17:12
-
1`Instant instant = Instant.ofEpochSecond(t); ZoneId zoneId = ZoneId.of("America/New_York"); ZonedDateTime z = ZonedDateTime.ofInstant(instant, zoneId);` for a specific ZoneId. – M.E. May 28 '20 at 22:41
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.

Arvind Kumar Avinash
- 71,965
- 6
- 74
- 110