Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Earliest and Latest ZonedDateTimes on Earth from an UTC reference time

I have a reference ZonedDateTime in UTC:

var ref = ZonedDateTime.parse("2022-01-01T14:00Z");

We must find the earliest and latest times on Earth based on the most extreme known TimeZones.

That would be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 2022-01-02T04:00+14
  • 2022-01-01T03:00-11

What is the most reliable way to achieve this?

I’m thinking about OffsetDateTime, but I’m not sure it will handle daylight times correctly. Are there constants for the minimum and maximum offsets and/or TZ?

>Solution :

You can do a stream on ZoneId.getAvailableZoneIds().

var instant = Instant.parse("2022-01-01T14:00:00Z");
var minMax = ZoneId.getAvailableZoneIds().stream()
    .mapToInt(x -> ZoneId.of(x).getRules().getOffset(instant).getTotalSeconds())
    .summaryStatistics();

var latestLocalTime = instant.atOffset(ZoneOffset.ofTotalSeconds(minMax.getMax())).toLocalDateTime();
var earliestLocalTime = instant.atOffset(ZoneOffset.ofTotalSeconds(minMax.getMin())).toLocalDateTime();
System.out.println(latestLocalTime);
System.out.println(earliestLocalTime);

Notice that this prints out, in Java 17:

2022-01-02T04:00
2022-01-01T02:00

The earliest time is different from what you expect. I looked into what this timezone is:

System.out.println(ZoneId.getAvailableZoneIds().stream()
    .map(ZoneId::of).min(Comparator.comparingInt(
        x -> x.getRules().getOffset(instant).getTotalSeconds()
    )));

It is apparently the timezone Etc/GMT+12. Despite its identifier, this timezone actually has an offset of -12 hours, because the Etc/GMT identifiers use the opposite signs. Anyway, UTC-12 is technically observed in Baker Island and Howland Island, according to Wikipedia.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading