Java DateFormat parse() doesn#39;t respect the timezone(Java DateFormat parse() 不尊重时区)
问题描述
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.
这篇关于Java DateFormat parse() 不尊重时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java DateFormat parse() 不尊重时区
基础教程推荐
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 多个组件的复杂布局 2022-01-01
- Java Swing计时器未清除 2022-01-01
