How to Convert a Date time value with UTC offset into GMT in java 7

GOPI picture GOPI · Dec 21, 2016 · Viewed 7.8k times · Source

I have a date time value 2016-12-21T07:48:36 with an offset of UTC+14. How to convert the datetime into equivalent standard GMT time.

I tried with sampleDateFormat.parse() method.But, I am not able to get the TimeZone object for UTC offset like.

sampleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC+14:00"))

Please help me to convert the UTC datetime into standard GMT time in Java 7.

Answer

Grodriguez picture Grodriguez · Dec 21, 2016

I will assume you have the original date as a string. Do the following:

  • Create a SimpleDateFormat and set the timezone to "GMT+14"
  • Parse the string value. You get a Date object
  • Set the timezone of the SimpleDateFormat to "UTC" (or use a different SimpleDateFormat instance)
  • Format the date (if you want the result as a string as well)

Example:

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

public class ConvertToUTC {
  public static void main(String[] args) throws Exception {

      String dateval = "2016-12-21T07:48:36";
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
      df.setTimeZone(TimeZone.getTimeZone("GMT+14"));
      Date date = df.parse(dateval);

      System.out.println(df.format(date)); // GMT+14

      df.setTimeZone(TimeZone.getTimeZone("UTC"));
      System.out.println(df.format(date)); // UTC
  }
}