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?
Java 8: How to create a ZonedDateTime from an Epoch value?
Asked Answered
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);
Instant instant = Instant.ofEpochSecond(t); ZoneId zoneId = ZoneId.of("America/New_York"); ZonedDateTime z = ZonedDateTime.ofInstant(instant, zoneId);
for a specific ZoneId. –
Hazel 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.
© 2022 - 2024 — McMap. All rights reserved.
ZonedDateTime.ofInstant(i, ZoneOffset.UTC)
for UTC – Systematology