How do I use java.time.ZoneId class?

java.time.ZoneId is a class in Java’s Date-Time API used to represent a time zone identifier. This identifier is used to get a ZoneRules, which then can be used to convert between an Instant and a LocalDateTime.

Here is how you can use the ZoneId class in a simple way:

package org.kodejava.datetime;

import java.time.ZoneId;
import java.time.ZonedDateTime;

public class ZoneIdExample {
    public static void main(String[] args) {
        // Get the system default ZoneId
        ZoneId defaultZoneId = ZoneId.systemDefault();
        System.out.println("System Default TimeZone : " + defaultZoneId);

        // Get ZoneId instance using the specified zone ID as a string
        ZoneId londonZoneId = ZoneId.of("Europe/London");
        System.out.println("London ZoneId : " + londonZoneId);

        // Get ZonedDateTime using ZoneId
        ZonedDateTime zonedDateTimeInLondon = ZonedDateTime.now(londonZoneId);
        System.out.println("Current date and time in London: " + zonedDateTimeInLondon);
    }
}

Output:

System Default TimeZone : Asia/Makassar
London ZoneId : Europe/London
Current date and time in London: 2024-01-19T06:43:23.076855Z[Europe/London]

In the above code:

  • ZoneId.systemDefault() is used to get the system default ZoneId.
  • ZoneId.of(String zoneId) is used to get a ZoneId instance using the specified zone ID as a string. You can get all available zone IDs by calling ZoneId.getAvailableZoneIds().
  • ZonedDateTime.now(ZoneId zoneId) is used to get the current date and time in the specified time zone.

Please note that the ZoneId is immutable and thread-safe, it ensures the class can be used safely in multithreaded systems.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.