将UTC时间戳转换为其他时区特定时间

时间:2017-03-01 19:58:44

标签: java datetime calendar jodatime simpledateformat

我正在处理需要将UTC时间戳转换为其他区域特定时间戳的要求。下面是不同时区的列表。

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;
}

以上代码适用于EST,PST,IST等时区,但对于列表中提到的其他时区,程序会给出错误的结果。请使用正确的解决方案更新我

1 个答案:

答案 0 :(得分:2)

您应该只使用带有偏移量的全名或GMT。

  

ID - TimeZone的ID,可以是缩写,例如" PST",全名,例如" America / Los_Angeles",或自定义ID,例如&#34 ; GMT-8:00&#34 ;.请注意,缩写的支持仅适用于JDK 1.1.x兼容性,应使用全名。

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


对于您提供的所有时区,有两种方法可以传递给该方法。

GMT OFFSET

只需将字符串作为"GMT {offset}"示例传递:

"GMT+0800"代替"CCST UTC+0800"

"GMT-0600"代替"CST UTC-0600"

等...

缩写(不推荐)

或者只是传递你也有的缩写:

"CST"代替"CST UTC+0800"

"EST代替"EST UTC-0500"

注意

尽管示例中使用的缩写似乎有效,但文档声明使用全名,因为缩写仅用于兼容性。