Rohith Kammula
Rohith Kammula

Reputation: 31

Converting UTC timestamp to other timezone specific time

I am working on requirement where I need to convert UTC time stamp to other zone specific timestamp.Below are the list of different timezones.

CET UTC+0100  
CST UTC+0800  
CST UTC-0600  
EST UTC-0500  
IST UTC+0530  
MET-1METDST   
SGT UTC+0800  
SST-8


public static String convertUTCTimeStampToOtherZoneTimestamp(Timestamp timestamp,String timeZone){
    String zoneSpecificTimeStamp="";
    try {
        DateFormat gmtFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TimeZone zoneTime = TimeZone.getTimeZone(timeZone);
        gmtFormat.setTimeZone(zoneTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String inputDateString = sdf.format(timestamp);
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
         zoneSpecificTimeStamp=gmtFormat.format(sdf.parse(inputDateString));
      } catch (ParseException e) {
        e.printStackTrace();
        return zoneSpecificTimeStamp;

      }
    return zoneSpecificTimeStamp;
}

The above code is work fine for timezones like EST,PST,IST but for other timezones mentioned in the list the program is giving wrong results. Please update me with the correct solution for this

Upvotes: 0

Views: 1374

Answers (1)

Eddie Martinez
Eddie Martinez

Reputation: 13910

You should only use the full name or GMT with offset.

ID - the ID for a TimeZone, either an abbreviation such as "PST", a full name such as "America/Los_Angeles", or a custom ID such as "GMT-8:00". Note that the support of abbreviations is for JDK 1.1.x compatibility only and full names should be used.

https://docs.oracle.com/javase/8/docs/api/java/util/TimeZone.html#getTimeZone-java.lang.String-


For all the time zones you have provided, there are two ways you can pass to the method.

GMT OFFSET

just pass the string as "GMT {offset}" examples:

"GMT+0800" instead of "CCST UTC+0800"

"GMT-0600" instead of "CST UTC-0600"

etc...

ABBREVIATIONS (Not Recommended)

Or just pass the abbreviation which you also have:

"CST" instead of "CST UTC+0800"

"EST instead of "EST UTC-0500"

NOTE

Although the abbreviations used in your examples seem to work, the documentation states to use full names, as the abbreviations are only for compatibility.

Upvotes: 2

Related Questions