SimpleDateFormat 忽略时区

SimpleDateFormat ignores TimeZone

我已经阅读了很多关于此的帖子,但是,我显然遗漏了一些东西。我有日期字符串和时区。我正在尝试按如下方式实例化日期对象:

        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC")); 
        java.util.Date dateObj = sdf.parse("2013-10-06 13:30:00");
        System.out.println(dateObj);

打印出来的是: Sun Oct 06 09:30:00 EDT 2013

我想要的是UTC格式的日期对象。没有一个转化为 EDT。我做错了什么?

谢谢。

这是因为您已经拥有一个 Date object does not store any timezone information. Date basically only stores the number of milliseconds since the epoch (Jan. 1, 1970). By default Date will use the timezone associated with the JVM. In order to preserve timezone information you should continue using the DateFormat 对象。

参见日期格式#format(日期): http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#format(java.util.Date)

以下应该能满足您的需求:

System.out.println(sdf.format(dateObj));

试试下面的代码,你会发现第一次解析的日期和设置时区后解析的日期不一样。实际上,日期是在正确的时区中按预期解析的。它在打印时为您提供了机器的默认 TZ。 您可以打印 dateObj.toGMTString() 来检查相同的内容,但已弃用。

    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Date dateObj = sdf.parse("2013-10-06 13:30:00");
    System.out.println(dateObj.toString());

    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    dateObj = sdf.parse("2013-10-06 13:30:00");
    System.out.println(dateObj.toString());