从GMT到CST的转换显示出7小时的差异

时间:2016-04-27 20:08:15

标签: java

我已使用此日期" 2016-04-26 12:00:00“,并使用以下功能转换为GMT和CST时期。我得到了以下日期。我不确定我在做错什么。

    1461672000000 UTC ——> Tue, 26 Apr 2016 12:00:00 GMT
    1461690000000  CST —> Tue, 26 Apr 2016 17:00:00 GMT

代码:

long epoch = 0;
String str = "2016-04-26 12:00:00";  
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("CST"));  //This GMT or CST
Date datenew = df.parse(str); //parsethe date
epoch = datenew.getTime(); //get the epoch time

1 个答案:

答案 0 :(得分:0)

正如埃里克森在评论中所提到的,你的期望似乎与实施相反;当您在 DateFormat 中设置 TimeZone 时,使用 DateFormat.parse()方法会导致字符串解析,就好像它一样来自 TimeZone (并将其转换为本地时间)。所以你注意到的结果是完全可以预期的。

要解决此问题,请改用 DateFormat.format()方法:

public static void main(String[] args) {
    String dateStr = "2016-04-26 12:00:00";
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    df.setTimeZone(TimeZone.getTimeZone("GMT"));

    Date gmtDate = null;
    try {
        gmtDate = df.parse(dateStr);
    }
    catch (ParseException e) {
        e.printStackTrace();
    }

    System.out.println("GMT TIME = " + df.format(gmtDate));
    df.setTimeZone(TimeZone.getTimeZone("CST"));
    System.out.println("CST TIME = " + df.format(gmtDate));
}

输出:

GMT TIME = 2016-04-26 12:00:00
CST TIME = 2016-04-26 07:00:00
相关问题