Java DateFormat parse()不遵守时区 [英] Java DateFormat parse() doesn't respect the timezone

查看:755
本文介绍了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

Sat Sep 24 20:10:51 CEST 2011

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月1日午夜)

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时间而不是日期 / 日历如果您在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()不遵守时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆