How to set the ZoneOffset for Berlin time zone
Asked Answered
S

1

10

I am getting the LocalDateTime two hours lesser than the real time. How can I get the offset time for Berlin, Germany for the code below?

LocalDateTime dateTime = LocalDateTime.ofEpochSecond(seconds, 0, ZoneOffset.UTC);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss", Locale.ENGLISH);
Strychnine answered 3/4, 2019 at 11:26 Comment(0)
H
13

Use a ZoneId and a ZonedDateTime.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss", Locale.ENGLISH);
ZoneId zone = ZoneId.of("Europe/Berlin");

long seconds = 1_556_000_000;

ZonedDateTime dateTime = Instant.ofEpochSecond(seconds).atZone(zone);
String formattedDateTime = dateTime.format(formatter);
System.out.println(formattedDateTime);

The output from this snippet is:

23.04.2019 08:13:20

My example seconds value corresponds to 06:13:20 UTC, so you’ve got your two hours offset from UTC respected.

Summer time (DST) is built in, so in winter you will get only 1 hour from UTC as you should. Historic changes in the offset work out of the box too, and known future changes (what happens in Germany after 2021 no one knows).

Heyman answered 10/4, 2019 at 8:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.