Java DateFormat parse() 不尊重时区

2022-01-15 00:00:00 format parsing date java
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("America/New_York"));
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
df.setTimeZone(TimeZone.getTimeZone("America/New_York"));

try {
    System.out.println(df.format(cal.getTime()));
    System.out.println(df.parse(df.format(cal.getTime())));
} catch (ParseException e) {
    e.printStackTrace();
}

结果如下:

2011-09-24 14:10:51 -0400

2011-09-24 14:10:51 -0400

2011 年 9 月 24 日星期六 20:10:51 CEST

Sat Sep 24 20:10:51 CEST 2011

为什么当我解析从 format() 获得的日期时,它不遵守时区?

Why when I parse a date I get from format() it doesn't respect the timezone?

推荐答案

你正在打印调用 Date.toString(),总是使用默认时区.基本上,您不应该将 Date.toString() 用于除调试以外的任何事情.

You're printing the result of calling Date.toString(), which always uses the default time zone. Basically, you shouldn't use Date.toString() for anything other than debugging.

不要忘记 Date 没有时区 - 它代表时间的瞬间,以 Unix 纪元以来的毫秒数(1 月的午夜1970 UTC).

Don't forget that a Date doesn't have a time zone - it represents an instant in time, measured as milliseconds since the Unix epoch (midnight on January 1st 1970 UTC).

如果您再次使用格式化程序格式化日期,那应该会得出与以前相同的答案.

If you format the date using your formatter again, that should come up with the same answer as before.

顺便说一句,我建议使用 Joda Time 而不是 Date/Calendar 如果你在 Java 中做大量的日期/时间工作;这是一个非常更好的 API.

As an aside, I would recommend the use of Joda Time instead of Date/Calendar if you're doing any significant amount of date/time work in Java; it's a much nicer API.

相关文章