86

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?

lospejos
  • 1,976
  • 3
  • 19
  • 35
rabejens
  • 7,594
  • 11
  • 56
  • 104

2 Answers2

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);
buræquete
  • 14,226
  • 4
  • 44
  • 89
Prisoner
  • 49,922
  • 7
  • 53
  • 105
  • 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