Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Tuesday, July 27, 2021

How to Convert Local Time to GMT in Java - Example Tutorial

Converting local time into GMT or any other timezone in Java is easy as Java has support for time zones. JDK has a class called java.util.Timezone which represents timezone and Java also has classes like SimpleDateFormat which can use Time zone while parsing or formatting dates. By using java.uti.TimeZone and java.text.SimpleDateFormat we can write a simple Java program to convert local time to GMT or any other time zone in Java. We have already seen examples of How to get current date and time in GMT and this Java program is an extension of that in order to convert time form one timezone to other timezones.

This article is in continuation of my previous basic Java tutorials like How to convert Double to String in Java , How to convert char to String in Java and how to write hashcode in Java. If you haven’t read them already you may find them useful.

Java program to convert local time to GMT or other Timezone

Java program to convert local time into GMT or other timezone
Here is a complete code example of converting local time into GMT timezone. As I said you can convert local time to any other timezone by just setting the current timezone for SimpleDateFormat as shown in this example. By the way, beware while using SimpleDateFormat in a multi-threading environment as SimpleDateFormat in Java is not thread safe.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

 * Simple Java program to convert local time into GMT or any other TimeZone in Java
 * SimpleDateFormat in Java can be used to convert Date from one timezone to other
 * @author Javin

public class TimeZoneConverter {

    public static void main(String args[]) {
     //Date will return local time in Java  
     Date localTime = new Date();
     //creating DateFormat for converting time from local timezone to GMT
     DateFormat converter = new SimpleDateFormat("dd/MM/yyyy:HH:mm:ss");
     //getting GMT timezone, you can get any timezone e.g. UTC
     System.out.println("local time : " + localTime);;
     System.out.println("time in GMT : " + converter.format(localTime));

local time : Wed Apr 11 05:48:16 VET 2012
time in GMT : 11/04/2012:10:18:16

That's all on how to convert local time into GMT or any other timezone in Java like UTC or EDT etc. while converting time from one timezone to another just keep an eye on day light saving as some Timezone falls under daylight time-saving zone.

Other Java Programming tutorials

1 comment :

Anonymous said...

AFAIK, new Date() instance in java is already timestamp in UTC(GMT). But when you print date, it prints in your machines local timezone else it is already in UTC.

Post a Comment