The Wayback Machine - https://web.archive.org/web/20240828080432/https://www.geeksforgeeks.org/java-util-timezone-class-set-2-example-timezone-class/
Open In App

Java.util.TimeZone Class (Set-2) | Example On TimeZone Class

Last Updated : 17 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

TimeZone class (the methods of this class was discussed in this article Java.util.TimeZone Class | Set 1) can be used in many cases like using TimeZone class we can get the time difference in term of hour and minute between two places.
Problem : How we can get time difference of time in terms of hours and minutes between two places of Earth?
Solution : To solve above situation, we must follow the following steps
 

  1. Get the Time Zone Id as input for both the places.
  2. Using this Time Zone Id find the Time Zone of both places.
  3. Using Time Zone Find the Date and Time of both places
  4. Find the difference between the Date and time of both places
  5. The difference is your answer for above question

You can get list of Time Zone Ids then you can go to this link (The data of column name TZ* of this link are Time Zone Ids. You can use those Id as Input.)
 

Java




// Java program to find time difference in term of hour and
// minute between two places.
 
import java.time.LocalDateTime;
import java.util.*;
 
public class TimeDifference {
 
    public static void main(String[] args)
    {
 
        // Take Ids of both places as Input
        Scanner sc = new Scanner(System.in);
 
        String TimeZoneId1 = sc.nextLine();
        String TimeZoneId2 = sc.nextLine();
 
        // Using Id of First place find LocalDateTime of that place
        TimeZone timezone1 = TimeZone.getTimeZone(TimeZoneId1);
 
        LocalDateTime dateTime1 = getDateTime(timezone1);
 
        // Using Id of Second place find LocalDateTime of that place
        TimeZone timezone2 = TimeZone.getTimeZone(TimeZoneId2);
 
        LocalDateTime dateTime2 = getDateTime(timezone2);
 
        // Print the Date and Time of Both TimeZones
        System.out.println("Date and Time of place having Id " + TimeZoneId1);
        System.out.println("Date - " + dateTime1.toLocalDate());
        System.out.println("Time - " + dateTime1.toLocalTime());
        System.out.println("Date and Time of place having Id " + TimeZoneId2);
        System.out.println("Date - " + dateTime2.toLocalDate());
        System.out.println("Time - " + dateTime2.toLocalTime());
 
        // Find the Difference in terms of minutes between both places
        long diffInMinutes =
            java.time.Duration.between(dateTime1, dateTime2).toMinutes();
        System.out.println("\nDifference in Hour is "
            + Math.abs(diffInMinutes / 60));
        System.out.println("Difference in Minute is "
            + Math.abs(diffInMinutes % 60));
    }
 
    static LocalDateTime getDateTime(TimeZone time)
    {
 
        // Using Time zone get calendar object
        Calendar cal = new GregorianCalendar(time);
 
        // using calendar object find the month, year, day, hour, minute
        int month = cal.get(Calendar.MONTH);
        int year = cal.get(Calendar.YEAR);
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
 
        /*
         * construct LocalDateTime object
        using month, year, day, hour, minute
        */
        LocalDateTime dateTime = LocalDateTime.of(year, month + 1, day,
                                                  hour, minute);
 
        return dateTime;
    }
}


Input: 
 

Asia/Chita
Asia/Yangon

Output: 
 

Date and Time of place having Id Asia/Chita
Date - 2018-04-25
Time - 04:16
Date and Time of place having Id Asia/Yangon
Date - 2018-04-25
Time - 01:46

Difference in Hour is 2
Difference in Minute is 30

Explanation : We are getting TimeZone object of the place using Id provided as Input then using method getDateTime we are getting current Date and Time of that place. The method getDateTime return LocalDateTime object we can get Date using toLocalDate() method of LocalDateTime class and Time using toLocalTime() method of LocalDateTime class. 
When we have current date and time of both place then we can find time difference in terms of hour and minute between both places.

 Sure, here’s an example of using the TimeZone class in Java:

Java




import java.util.TimeZone;
 
public class Main {
    public static void main(String[] args) {
        // Getting the default time zone
        TimeZone defaultZone = TimeZone.getDefault();
        System.out.println("Default time zone: " + defaultZone.getID());
 
        // Setting the time zone to Los Angeles
        TimeZone losAngelesZone = TimeZone.getTimeZone("America/Los_Angeles");
        TimeZone.setDefault(losAngelesZone);
        System.out.println("Current time zone: " + TimeZone.getDefault().getID());
 
        // Displaying available time zones
        String[] availableZones = TimeZone.getAvailableIDs();
        System.out.println("Available time zones:");
        for (String zone : availableZones) {
            System.out.println(zone);
        }
    }
}


Output:

Default time zone: America/New_York
Current time zone: America/Los_Angeles
Available time zones:
…
America/Cuiaba
America/Curacao
America/Danmarkshavn
America/Dawson
America/Dawson_Creek
America/Denver
America/Detroit
…
 

In this example, we’re using the TimeZone class to get and set the time zone, as well as to display a list of available time zones.

First, we’re using the getDefault() method to get the default time zone of the system and printing it out. Then, we’re setting the time zone to Los Angeles using the getTimeZone() method and the setDefault() method. We’re then printing out the current time zone to confirm that it has been set to Los Angeles.

Finally, we’re using the getAvailableIDs() method to get a list of all available time zones and printing them out in the console.

Overall, the TimeZone class in Java is useful for working with time zones and performing various operations on them, such as getting the default time zone, setting the time zone, and getting a list of available time zones.

Here are some advantages and disadvantages of using the TimeZone class in Java:

Advantages:

  1. The TimeZone class provides a standard way to work with time zones, making it easier to write portable code that works across different platforms and systems.
  2. It offers a wide range of functionality for working with time zones, such as getting the default time zone, setting the time zone, getting a list of available time zones, and converting times between different time zones.
  3. It can help prevent errors that can occur when working with time zones manually, such as forgetting to adjust for daylight saving time or forgetting to account for differences in time zones.

Disadvantages:

  1. The TimeZone class can be complex and difficult to use, particularly for developers who are new to working with time zones.
  2. The large number of available time zones can make it difficult to select the correct one for a given use case.
  3. The TimeZone class can be slow and resource-intensive, particularly when performing complex operations that involve many time zone conversions.
    Overall, the TimeZone class is a useful tool for working with time zones in Java, but it may not be the best choice for all use cases. Developers
  4. should carefully consider their specific needs and use cases when deciding whether or not to use the TimeZone class, and should be prepared to invest time and effort into learning how to use it effectively.


Similar Reads

Java.util.TimeZone Class | Set 1
TimeZone class is used to represents a time zone offset, and also figures out daylight savings.What is a Time Zone and Time Offset?"Time Zone" is used to describe the current time for different areas of the world. It refers to one of the specific regions out of the 24 total regions in the world that are divided up by longitude. Within each one of t
7 min read
Java.util.BitSet class in Java with Examples | Set 1
BitSet is a class defined in the java.util package. It creates an array of bits represented by boolean values. Constructors: BitSet class Constructors / \ BitSet() BitSet(int no_Of_Bits)BitSet() : A no-argument constructor to create an empty BitSet object. BitSet(int no_Of_Bits): A one-constructor with an integer argument to create an instance of t
2 min read
Java.util.BitSet class methods in Java with Examples | Set 2
Methods discussed in this post: BitSet class methods. / / | | \ \ set() xor() clone() clear() length() cardinality() We strongly recommend to refer below set 1 as a prerequisite of this. BitSet class in Java | Set 1 set() : java.util.BitSet.set() method is a sets the bit at the specified index to the specified value. Syntax:public void set(int bitp
4 min read
Java.util.Locale Class in Java | Set 1
As the name suggests util.Locale Class is used to perform locale tasks and provides locale information for the user. Declaration : public final class Locale extends Object implements Cloneable, Serializable Constructors : Locale(String L): Creates Locale from the given language code.Locale(String L, String C): Creates Locale from the given language
4 min read
Java.util.Locale Class in Java | Set 2
Java.util.Locale Class in Java | Set 1 More methods: getDisplayVariant() : java.util.Locale.getDisplayVariant() displays variant of the Locale Syntax : public final String getDisplayVariant() Parameters : ---- Return : ----------- getDisplayVariant(Locale in) : java.util.Locale.Locale in(Locale in) returns the variant of "in" locale. Syntax : publi
3 min read
Java.util.ArrayDeque Class in Java | Set 1
java.util.ArrayDeque class describes an implementation of a resizable array structure which implements the Deque interface. Array deques has not immutable and can grow as necessary. They are not thread-safe and hence concurrent access by multiple threads is not supported unless explicitly synchronized. Null elements are invalid in this structure. M
5 min read
Java.util.ArrayDeque Class in Java | Set 2
Java.util.ArrayDeque Class in Java | Set 1 More Methods of util.ArrayDeque Class : 16. offer(Element e) : java.util.ArrayDeque.offer(Element e) : inserts element at the end of deque. Syntax : public boolean offer(Element e) Parameters : e - element to add Return : true, if element is added else; false 17. offerFirst(Element e) : java.util.ArrayDequ
5 min read
java.util.Currency methods with example
This class represents currency. Here, currency is identified by their ISO 4217 currency codes. The purpose of ISO 4217 is to establish internationally recognized codes for the representation of currencies. Currencies can be represented in the code in two ways: a three-letter alphabetic code and a three-digit numeric code. util.Currency methods in J
3 min read
Java.util.BitSet.set() method in Java
There are four variants of set() method.This article depicts about all of them, as follows: 1. set(int Index) : This method sets the bit at the specified index to true i.e adds a value. Declaration : public void set(int bitIndex) Parameters : Index : a bit index. Result : This method does not return a value. Exception : IndexOutOfBoundsException :
3 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java.util.concurrent.RecursiveAction class in Java with Examples
RecursiveAction is an abstract class encapsulates a task that does not return a result. It is a subclass of ForkJoinTask, which is an abstract class representing a task that can be executed on a separate core in a multicore system. The RecursiveAction class is extended to create a task that has a void return type. The code that represents the compu
3 min read
Java.util.concurrent.Phaser class in Java with Examples
Phaser's primary purpose is to enable synchronization of threads that represent one or more phases of activity. It lets us define a synchronization object that waits until a specific phase has been completed. It then advances to the next phase until that phase concludes. It can also be used to synchronize a single phase, and in that regard, it acts
7 min read
Java.util.concurrent.RecursiveTask class in Java with Examples
RecursiveTask is an abstract class encapsulates a task that returns a result. It is a subclass of ForkJoinTask. The RecursiveTask class is extended to create a task that has a particular return type. The code that represents the computational portion of the task is kept within the compute() method of RecursiveTask. RecursiveTask class is mostly use
2 min read
Java.util.zip.DeflaterInputStream class in Java
Implements an input stream filter for compressing data in the "deflate" compression format. Constructor and Description DeflaterInputStream(InputStream in) : Creates a new input stream with a default compressor and buffer size. DeflaterInputStream(InputStream in, Deflater defl) : Creates a new input stream with the specified compressor and a defaul
3 min read
Java.util.zip.InflaterOutputStream class in Java
This class implements an output stream filter for uncompressing data stored in the "deflate" compression format. Constructors InflaterOutputStream(OutputStream out) : Creates a new output stream with a default decompressor and buffer size. InflaterOutputStream(OutputStream out, Inflater infl) : Creates a new output stream with the specified decompr
3 min read
Java.util.zip.InflaterInputStream class in Java
This class implements a stream filter for uncompressing data in the "deflate" compression format. It is also used as the basis for other decompression filters, such as GZIPInputStream. Constructors InflaterInputStream(InputStream in) : Creates a new input stream with a default decompressor and buffer size. InflaterInputStream(InputStream in, Inflat
3 min read
Java.util.zip.ZipOutputStream class in Java
This class implements an output stream filter for writing files in the ZIP file format. Includes support for both compressed and uncompressed entries. Constructor : ZipOutputStream(OutputStream out) : Creates a new ZIP output stream. ZipOutputStream(OutputStream out, Charset charset) : Creates a new ZIP output stream. Methods: void close() : Closes
3 min read
Java.util.jar.JarEntry class in Java
This class is used to represent a JAR file entry. Constructors : JarEntry(JarEntry je) : Creates a new JarEntry with fields taken from the specified JarEntry object. JarEntry(String name) : Creates a new JarEntry for the specified JAR file entry name. JarEntry(ZipEntry ze) : Creates a new JarEntry with fields taken from the specified ZipEntry objec
2 min read
Java.util.zip.GZIPInputStream class in Java
This class implements a stream filter for reading compressed data in the GZIP file format. Constructors GZIPInputStream(InputStream in) : Creates a new input stream with a default buffer size. GZIPInputStream(InputStream in, int size) : Creates a new input stream with the specified buffer size. Methods : void close() : Closes this input stream and
2 min read
Java.util.zip.ZipEntry class in Java
This class is used to represent a ZIP file entry. Constructors ZipEntry(String name) : Creates a new zip entry with the specified name. ZipEntry(ZipEntry e) : Creates a new zip entry with fields taken from the specified zip entry. Methods: Object clone() : Returns a copy of this entry. Syntax :public Object clone() Overrides: clone in class Object
4 min read
Java.util.jar.JarInputStream class in Java
The JarInputStream class is used to read the contents of a JAR file from any input stream. It extends the class java.util.zip.ZipInputStream with support for reading an optional Manifest entry. The Manifest can be used to store meta-information about the JAR file and its entries. Constructors JarInputStream(InputStream in) : Creates a new JarInputS
3 min read
Java.util.zip.ZipInputStream class in Java
This class implements an input stream filter for reading files in the ZIP file format. Includes support for both compressed and uncompressed entries. Constructors: ZipInputStream(InputStream in) : Creates a new ZIP input stream. ZipInputStream(InputStream in, Charset charset) : Creates a new ZIP input stream Methods : int available() : Returns 0 af
3 min read
Java.util.PriorityQueue class in Java
It is a priority queue based on priority heap. Elements in this class are in natural order or depends on the Constructor we used at this the time of construction. It doesn't permit null pointers. It doesn't allow inserting a non-comparable object, if it relies on natural ordering. Constructors: PriorityQueue(): Creates a PriorityQueue with the defa
6 min read
Java.util.Random class in Java
Random class is used to generate pseudo-random numbers in java. An instance of this class is thread-safe. The instance of this class is however cryptographically insecure. This class provides various method calls to generate different random data types such as float, double, int. Constructors: Random(): Creates a new random number generator Random(
4 min read
Java.util.TimerTask class in Java
TimerTask is an abstract class defined in java.util package. TimerTask class defines a task that can be scheduled to run for just once or for repeated number of time. In order to define a TimerTask object, this class needs to be implemented and the run method need to be overridden. The run method is implicitly invoked when a timer object schedules
3 min read
Java.util.Timer Class in Java
Timer class provides a method call that is used by a thread to schedule a task, such as running a block of code after some regular instant of time. Each task may be scheduled to run once or for a repeated number of executions. Each timer object is associated with a background thread that is responsible for the execution of all the tasks of a timer
6 min read
Java.util.Dictionary Class in Java
The java.util.Dictionary class in Java is an abstract class that represents a collection of key-value pairs, where keys are unique and are used to access the values. It was part of the Java Collections Framework introduced in Java 1.2 but has been largely replaced by the java.util.Map interface since Java 1.2. The Dictionary class is an abstract cl
7 min read
Java.util.Observable class in Java
java.util.Observable is used to create subclasses that other parts of the program can observe. When an object of such subclass undergoes a change, observing classes are notified. The update( ) method is called when an observer is notified of a change. Note: Observing class must implement the Observer interface, which defines the update( ) method. A
8 min read
Java.util.UUID class in Java
A class that represents an immutable universally unique identifier (UUID). A UUID represents a 128-bit value. There exist different variants of these global identifiers. The methods of this class are for manipulating the Leach-Salz variant, although the constructors allow the creation of any variant of UUID (described below). There are four differe
7 min read
Java.util.Objects class in Java
Java 7 has come up with a new class Objects that have 9 static utility methods for operating on objects. These utilities include null-safe methods for computing the hash code of an object, returning a string for an object, and comparing two objects. Using Objects class methods, one can smartly handle NullPointerException and can also show customize
7 min read
Article Tags :
Practice Tags :