Get & Set default timezone of java virtual machine (JVM) – example

  • We would like to get/set the default timezone in java.
    • TimeZone represents a time zone offset, and also figures out daylight savings.
  • We will use package java.util.TimeZone to get/set default time zone.

1. Important methods of TimeZone class

Method Name Description
static TimeZone getDefault() Gets the default TimeZone of the Java virtual machine.
static TimeZone getTimeZone(String ID) Gets the TimeZone for the given ID.
static void setDefault(TimeZone zone) Sets the TimeZone that is returned by the getDefault method.
String getDisplayName() Returns a long standard time name of this TimeZone suitable for presentation to the user in the default locale.
String getID() Gets the ID of this time zone.
abstract int getRawOffset() Returns the amount of time in milliseconds to add to UTC to get standard time in this time zone.

2. Program: Get & Set default timezone of java virtual machine (JVM)

package org.learn;

import java.util.TimeZone;

public class DemoTimeZone {
    public static void main(String[] args) {
        //Get default time zone
        TimeZone timeZone = TimeZone.getDefault();
        System.out.println("1. Default time zone is:");
        System.out.println(timeZone);

        //Setting default time zone
        System.out.println("2. Setting UTC as default time zone");
        TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
        //Setting UTC time zone
        TimeZone.setDefault(utcTimeZone);

        //Now get default time zone
        timeZone = TimeZone.getDefault();
        System.out.println(timeZone);

        System.out.println("3. Exploring properties of timezone object : ");
        System.out.printf("3.1. DisplayName = %s, ID = %s, offset = %s",
                        timeZone.getDisplayName(),timeZone.getID(),timeZone.getRawOffset());
    }
}

3. Output: Get & Set default timezone of java virtual machine (JVM)

1. Default time zone is:
sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null]
2. Setting UTC as default time zone
sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
3. Exploring properties of timezone object : 
3.1. DisplayName = Coordinated Universal Time, ID = UTC, offset = 0
Scroll to Top