The java.util.GregorianCalendar.getTimeZone() method is an in-built method in Java which fetches the time zone and returns the TimeZone object associated with this calendar.
Syntax:
public TimeZone getTimeZone()
Parameters: This method does not accept any parameter.
Return Values: This method returns a TimeZone object which denotes the time zone of this calendar.
Examples:
Input : Mon Jul 23 19:45:33 UTC 2018 Output : Coordinated Universal Time Input : Wed Oct 23 20:02:52 UTC 2019 cal.setTimeZone(TimeZone.getTimeZone("CST")); Output : Central Standard Time
Below programs illustrate the java.util.GregorianCalendar.getTimeZone() function in Java:
Program 1:
Java
// Java Program to illustrate // GregorianCalendar.getTimeZone() // function import java.io.*; import java.util.*; class GFG { public static void main(String[] args) { // Create a new calendar GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance(); //Display the current date and time System.out.println( "Current Date and Time : " + cal.getTime()); /* Creating a Time Zone object and storing this TimeZone */ TimeZone t = cal.getTimeZone(); // Display the time zone System.out.println( "Time Zone : " + t.getDisplayName()); } } |
Current Date and Time : Wed Jul 25 11:25:16 UTC 2018 Time Zone : Coordinated Universal Time
Program 2: In this program, we use setTimeZone() to change the current time zone and then fetch the new time zone using getTimeZone() method.
Java
// Java Program to illustrate // GregorianCalendar.getTimeZone() // function import java.io.*; import java.util.*; class GFG { public static void main(String[] args) { // Create a new calendar GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance(); // Display the current date and time System.out.println( "Current Date and Time : " + cal.getTime()); // Changing the current time zone cal.setTimeZone(TimeZone.getTimeZone( "CST" )); /* Creating a Time Zone object and storing the TimeZone */ TimeZone t = cal.getTimeZone(); // Display the time zone System.out.println( "Time Zone : " + t.getDisplayName()); } } |
Current Date and Time : Wed Jul 25 11:25:22 UTC 2018 Time Zone : Central Standard Time
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#getTimeZone()