The following code snippet will show you how to convert the old java.util.TimeZone
to java.time.ZoneId
introduced in Java 8. In the first line of our main()
method we get the default timezone using the TimeZone.getDefault()
and convert it to ZoneId
by calling the toZoneId()
method. In the second example we create the TimeZone
object by calling the getTimeZone()
and pass the string of timezone id. To convert it to ZoneId
we call the toZoneId()
method.
package org.kodejava.datetime;
import java.time.ZoneId;
import java.util.TimeZone;
public class TimeZoneToZoneId {
public static void main(String[] args) {
ZoneId zoneId = TimeZone.getDefault().toZoneId();
System.out.println("zoneId = " + zoneId);
TimeZone timeZoneUsPacific = TimeZone.getTimeZone("US/Pacific");
ZoneId zoneIdUsPacific = timeZoneUsPacific.toZoneId();
System.out.println("zoneIdUsPacific = " + zoneIdUsPacific);
}
}
This snippet prints the following output:
zoneId = Asia/Shanghai
zoneIdUsPacific = US/Pacific
To convert the other way around you can do it like the following code snippet. Below we convert the ZoneId
to TimeZone
by using the TimeZone.getTimeZone()
method and pass the ZoneId.systemDefault()
which return the system default timezone. Or we can create ZoneId
using the ZoneId.of()
method and specify the timezone id and then pass it to the getTimeZone()
method of the TimeZone
class.
package org.kodejava.datetime;
import java.time.ZoneId;
import java.util.TimeZone;
public class ZoneIdToTimeZone {
public static void main(String[] args) {
TimeZone timeZone = TimeZone.getTimeZone(ZoneId.systemDefault());
System.out.println("timeZone = " + timeZone.getDisplayName());
TimeZone timeZoneUsPacific = TimeZone.getTimeZone(ZoneId.of("US/Pacific"));
System.out.println("timeZoneUsPacific = " + timeZoneUsPacific.getDisplayName());
}
}
And here are the output of the code snippet above:
timeZone = China Standard Time
timeZoneUsPacific = Pacific Standard Time
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023