How to Convert Local Time to GMT in Java?
Time conversion from IST or any standard time to GMT is necessary for locals to understand and reciprocate their international clients if they are connected overseas in terms of work or any purpose. Today we will have a look at a code where we convert the standard time of any country to GMT.
Here we would use the SimpleDateFormat to convert the local Time in GMT. It is available in class as mentioned:
Methods: One can use different methods like SimpleDateFormat or maybe even Instance() method. They are very easy and helpful methods. We can also use calendar and time methods to do so.
Method 1: Using format() method of SimpleDateFormat class
The format() method of DateFormat class in Java is used to format a given date into a Date/Time string. Basically, the method is used to convert this date and time into a particular format i.e., mm/dd/yyyy.
public final String format(Date date)
Parameters: The method takes one parameter date of Date object type and refers to the date whose string output is to be produced.
Return Value: The method returns Date or time in string format of mm/dd/yyyy.
- Here we would simply first print our local time
- Then convert it to GMT using SimpleDateFormat
- Then print both the time zones.
local Time:Thu Feb 04 11:34:15 UTC 2021 Time IN Gmt : 04/02/2021 11:34:15
Method 2: Using instance() method of SimpleDateFormat class
As in the above method we used SimpleDateFormat, we will now use the instant method to get the time. The SimpleDateFormat can be used in different ways, now the instant method can be used to get the UTC or GMT.
- We will use the Instant method to get the time proper time
- It can be importing the complete time class
Local : 2021-02-04T10:40:34.436700Z[Etc/UTC] GMT : 2021-02-04T10:40:34.547680Z