尴尬的 Java 日期创建行为
当我尝试创建两个日期时,我刚刚遇到了 Java 的 Date 类的一个非常奇怪的行为:
Date startDate = new Date(1282863600000L);
System.out.println(startDate);
Date endDate = new Date(1321919999000L);
System.out.println(endDate);
输出分别是:
Fri Aug 27 00:00:00 BST 2010 Mon Nov 21 23:59:59 GMT 2011
有人见过类似的东西吗?两个日期都以相同的方式初始化,但打印时第一个显示为 BST,后者显示为 GMT?
我试图找到对此的解释,但我没有。有人可以帮助我吗?
提前致谢!
I've just came upon a very strange behaviour of Java's Date class when I try to create two dates consequently:
Date startDate = new Date(1282863600000L);
System.out.println(startDate);
Date endDate = new Date(1321919999000L);
System.out.println(endDate);
The output is respectively:
Fri Aug 27 00:00:00 BST 2010 Mon Nov 21 23:59:59 GMT 2011
Has anyone seen something like that? Both date are initialized in an identical manner but when printed the first is shown in BST and the latter in GMT?
I tried to find explanation about that but I didn't. Can someone help me?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是有记录的行为。
来自
Date.toString()
:您使用的区域设置使用英国夏令时,并创建一个适用夏令时规则的日期。这将是本地用户当时期望的日期形式。
This is documented behaviour.
From
Date.toString()
:You are using a locale that uses British Summer Time and creating a date where a day-light-saving rule applies. This would be the expected form of the date at that time to a local user.
对我来说,这段代码的输出是
确切的结果取决于您系统上使用的默认 Java 语言环境。
区别在于 CEST 是中欧夏令时,而 CET 是欧洲中部时间(即不是夏令时)。
您似乎正在英国语言环境中运行(
en_GB
或类似语言),因此您的输出显示 英国夏令时间和格林威治标准时间分别。您指定的第一个日期属于各自的夏季时间,而第二个日期则不然。因此,Java 会为每个区域/时间组合选择适当的时区。
For me the output of this code is
The exact result depends on the default locale Java is using on your system.
The difference is that CEST is the central european summer time, while CET is the central european time (i.e. not summer time).
You seem to be running in a british locale (
en_GB
or similar), so your output shows the British Summer Time and the Greenwich Mean Time respectively.The first date you specify falls into the respective summer times and the second doesn't. So Java chooses the appropriate time zone for each locale/time combination.
在尝试了不同的
long
值之后,我得到了以下结果:输出是:
请注意,将 long 从
1284245999999L
增加1
到1284246000000L
由于从标准时间到夏令时的过渡,让我们“回到过去”。这就是 Java 时间计算的行为方式 - 自 1970 年 1 月 1 日以来的毫秒数不变,但它表示的时间基于时区。
After a lovely session of trying different
long
values I got this:The output was:
Note that incrementing the long by
1
from1284245999999L
to1284246000000L
takes us "back in time" because of the transition from standard time to daylight savings time.That is how Java time calculation behaves - the number of milliseconds since 1/1/1970 does not change, but the time it represents is based on the timezone.