TimeZone.getTimeZone(ZoneId) in Java

TimeZone.getTimeZone(ZoneId): This method is available in java.util.TimeZone class of Java.

Syntax:

TimeZone java.util.TimeZone.getTimeZone(ZoneId zoneId)

This method takes one argument. This method gets the TimeZone for the given zoneId.

Parameters: One parameter is required for this method.

zoneId: a ZoneId from which the time zone ID is obtained.

Returns: the specified TimeZone, or the GMT zone if the given IDcannot be understood.

Throws:

NullPointerException - if zoneId is null.

Approach 1: When no exception

Java

import java.time.ZoneId;
import java.util.TimeZone;

public class TimeZonegetTimeZone2 {
    public static void main(String[] args) {

        ZoneId zoneId = ZoneId.systemDefault();
        System.out.println(TimeZone.getTimeZone(zoneId));
    }
}

Output:

sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=7,lastRule=null]



Approach 2: NullPointerException

Java

import java.time.ZoneId;
import java.util.TimeZone;

public class TimeZonegetTimeZone2 {
    public static void main(String[] args) {

        ZoneId zoneId = null;
        System.out.println(TimeZone.getTimeZone(zoneId));
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.time.ZoneId.getId()" because "zoneId" is null at java.base/java.util.TimeZone.getTimeZone(TimeZone.java:531)


No comments:

Post a Comment