問(wèn)題描述
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();
}
結(jié)果如下:
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
為什么當(dāng)我解析從 format() 獲得的日期時(shí),它不遵守時(shí)區(qū)?
Why when I parse a date I get from format() it doesn't respect the timezone?
推薦答案
你正在打印調(diào)用 Date.toString()
,總是使用默認(rèn)時(shí)區(qū).基本上,您不應(yīng)該將 Date.toString()
用于除調(diào)試以外的任何事情.
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
沒(méi)有時(shí)區(qū) - 它代表時(shí)間的瞬間,以 Unix 紀(jì)元以來(lái)的毫秒數(shù)(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).
如果您再次使用格式化程序格式化日期,那應(yīng)該會(huì)得出與以前相同的答案.
If you format the date using your formatter again, that should come up with the same answer as before.
順便說(shuō)一句,我建議使用 Joda Time 而不是 Date
/Calendar
如果你在 Java 中做大量的日期/時(shí)間工作;這是一個(gè)非常更好的 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.
這篇關(guān)于Java DateFormat parse() 不尊重時(shí)區(qū)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!