Get Daylight Saving Transition Dates For Time Zones in Java

Viewed 22119

I'd like to know the simplest way, in Java, to get a list of dates in the future where daylight savings time will change.

One rather inellegant way to do this would be to simply iterate over a bunch of years' worth of days, testing them against TimeZone.inDaylightTime(). This will work, and I'm not worried about efficiency since this will only need to run every time my app starts, but I wonder if there's a simpler way.

If you're wondering why I'm doing this, it's because I have a javascript app which needs to handle third-party data containing UTC timestamps. I want a reliable way to translate from GMT to EST on the client side. See Javascript -- Unix Time to Specific Time Zone I've written some javascript which will do it, but I want to get precise transition dates from the server.

2 Answers

java.time

The modern answer uses java.time, the modern Java date and time API.

    ZoneId zone = ZoneId.of("Europe/London");
    ZoneRules rules = zone.getRules();
    ZonedDateTime now = ZonedDateTime.now(zone);
    ZoneOffsetTransition transition = rules.nextTransition(now.toInstant());
    Instant max = now.plusYears(15).toInstant();
    while (transition != null && transition.getInstant().isBefore(max)) {
        System.out.println(transition);
        transition = rules.nextTransition(transition.getInstant());
    }

Output, abbreviated:

Transition[Overlap at 2019-10-27T02:00+01:00 to Z]
Transition[Gap at 2020-03-29T01:00Z to +01:00]
Transition[Overlap at 2020-10-25T02:00+01:00 to Z]
Transition[Gap at 2021-03-28T01:00Z to +01:00]
Transition[Overlap at 2021-10-31T02:00+01:00 to Z]
Transition[Gap at 2022-03-27T01:00Z to +01:00]
Transition[Overlap at 2022-10-30T02:00+01:00 to Z]
(cut)
Transition[Overlap at 2033-10-30T02:00+01:00 to Z]
Transition[Gap at 2034-03-26T01:00Z to +01:00]

I would not put too much trust in the data, though. I am not sure what happens with time in the UK after Brexit (and after EU may abandon summer time (DST) in 2021).

Link: Oracle tutorial: Date Time explaining how to use java.time.

Related