Is there any way to convert ZoneOffset to ZoneId in Java 8?

216 Views Asked by At

I am working on a project wherer i have limited zoneid and i am getting zoneoff set from front-end so that's why i want to convert time off set into zoneid in java. is there any way to convert zoneoffset into zone id.

3

There are 3 best solutions below

5
On

ZoneOffset is a kind of ZoneId! See the declaration in the documentation.

public final class ZoneOffset
extends ZoneId

There is no need for any extra steps. You can directly pass ZoneOffset objects to things that expects ZoneIds.


If what you actually want to do is to find a region-based zone ID, e.g. Europe/London, from solely a ZoneOffset, there will likely be multiple such IDs that have the offset right now, or at any other particular instant.

To find the list of region-based IDs that is at a specified offset at a particular instant, you can do:

ZoneId.getAvailableZoneIds().stream()
    .map(ZoneId::of)
    .filter(id -> id.getRules().getOffset(theSpecifiedInstant).equals(theSpecifiedOffset))
    .collect(Collectors.toList());
    // or just .toList() in Java 16+
1
On

Use the available ZoneRules to find a suitable matching zone. There's no direct conversion ZoneOffset represents a fixed offset from UTC, whereas a ZoneId represents a geographical region with varying offsets due to daylight saving time changes. Based on the above you can build one yourself to make that conversion. Here is a template

0
On

Java 11+: ZoneRules.getStandardOffset(Instant)

Gets the standard offset for the specified instant in this zone.

This provides access to historic information on how the standard offset has changed over time. The standard offset is the offset before any daylight saving time is applied. This is typically the offset applicable during winter.

That means if you have a ZoneId, you can get its rules by calling getRules() and get the standard offset of the Instant you provide to getStandardOffset(Instant). You could use Instant.now() as soon as you have the ZoneId from the front end.

example

public static void main(String[] args) {
    // example input
    ZoneId perth = ZoneId.of("Australia/Perth");
    // define an Instant
    Instant now = Instant.now();
    // determine the standard offset from the rules of the zone
    ZoneOffset perthStandardOffset = perth.getRules()
                                          .getStandardOffset(now);
    // and print it
    System.out.println(
            String.format("%s has a standard offset of %s at %s",
                          perth, perthStandardOffset,
                          now.atZone(ZoneOffset.UTC))
            );
}

output

Australia/Perth has a standard offset of +08:00 at 2023-06-07T07:41:38.082053Z