Java TimeZone With Examples

Java TimeZone class represents a time zone offset, and also figures out daylight savings. Time zone is a region of the globe that observes a uniform standard time for all the purposes. Time zone is important for programs as well as it gives the user a feel of the application being local to the user.

Java TimeZone

Java TimeZone class is used for implementation and manipulation of various TimeZone across the program. This class is part of the java.util package and should be used along with the Calendar class.

Starting from Java 8, for date time API the time zones are represented by the java.time.ZoneId class. This is needed only if you are using the Java 8 date time classes like the ZonedDateTimeclass. If you use a Calendar class from the Java 7 and earlier date time API you can still use the java.util.TimeZone class.

Creating Java TimeZone instance

There are two ways of creating a TimeZone object.

  1. Using getDefault() method: TimeZone class contains a getDefault() method which provides a TimeZone object based on the time zone in which the application or the program is running.

    If the above mentioned program is running in India, the default time zone that is IST will be provided as the TimeZone object.
  2. Using getTimeZone() method: TimeZone class contains getTimeZone() method, where the input parameter for the method is a time zone ID.

We discussed in the introduction section that TimeZone should be used along with Calendar. Let’s try to understand how it should be done.

Using TimeZone with Calendar

For using TimeZone with Calendar we need an instance of the Calendar class. We will look at an example of how to get time zone from Calendar.

Now if we want to set the time zone for Calendar instance we can perform that task as follows.

Java TimeZone Methods

  • getDisplayName(): A standard time name of the TimeZone which suitable for presentation to the user in the default locale.
  • getID(): Returns the ID of the time zone.
  • getOffset(long date): Returns the offset of this time zone from UTC at the specified date.

We can use time zone conversion as well for converting the time zone based on the ID that is provided, this use case is needed when the application is running in two specific time zones.

Java TimeZone Conversion

Here is an example for converting a date from Calendar to different time zones.

Output produced by above example:

In the example above, the time denoted by milliseconds is same for America and Asia but there is a difference in the hour field representing the change in the time zones.

Java TimeZone ID

We can get the list of ID available for using with TimeZone by using getAvailableIDs() and iterating through the result of the method.

That’s all for Java TimeZone class.

Reference: Oracle Documentation

By admin

Leave a Reply

%d bloggers like this: