DateFormat 正在打印 new Date(0) 作为纪元 + 1小时

发布于 2024-12-04 04:35:44 字数 278 浏览 0 评论 0原文

以下测试失败:

DateFormat df = new SimpleDateFormat("HH:mm:ss z");
assertEquals("00:00:00 GMT", df.format(new Date(0)));

预期为“00:00:00 GMT”,但实际为“01:00:00 GMT”

有人可以指出我哪里愚蠢吗?

我花在这个问题上的时间比我用 Joda-Time 替换所有内容的时间还要长。某处有一个教训。

The following test fails:

DateFormat df = new SimpleDateFormat("HH:mm:ss z");
assertEquals("00:00:00 GMT", df.format(new Date(0)));

expected "00:00:00 GMT" but was "01:00:00 GMT"

Could someone point out where I'm being stupid please?

I've spent longer looking at this than is would have taken me to just replace everything with Joda-Time. There's a lesson there somewhere.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我要还你自由 2024-12-11 04:35:44

问题在于,Java 在 1970 年欧洲/伦敦时区缩写名称方面存在错误。1970

年冬天,英国仍采用 UTC+1 - 但 Java 认为它仍称为“GMT”。所以你看到的是 1970 年 1 月 1 日午夜 UTC 的本地时间...只是我们习惯了 GMT=UTC,这就是它令人困惑的原因。

(顺便说一句,即使是现在,转换为 Joda Time 仍然值得。像瘟疫一样避免使用内置库:)

Joda Time 将时区缩写打印为“BST”。这似乎同样奇怪,因为它显然不是夏季时间……但这里的“S”可能是标准时间,因为那是在“英国标准时间实验”期间。有关详细信息,请参阅维基百科

(请注意,UTC 本身在 Unix 时代甚至不存在 - 它是在 1972 年引入的。为了这个答案,我假设 UTC 是一个预谋的 :)

The problem is that Java has a bug around the name of the Europe/London time zone abbreviation in 1970.

In the winter of 1970, the UK was still on UTC+1 - but Java believes it's still called "GMT". So what you're seeing is the local time at midnight UTC on January 1st 1970... it's just that we're used to GMT=UTC, which is why it's confusing.

(As a side note, it would still be worth converting to Joda Time even now. Avoid the built-in libraries like the plague :)

Joda Time prints the time zone abbreviation as "BST". This seems equally bizarre given that it clearly wasn't summer time... but it's possible that the "S" here standards for Standard, as that was during the period of the "British Standard Time experiment". See Wikipedia for details.

(Note that UTC itself didn't even exist at the Unix epoch - it was introduced in 1972. I'm assuming a proleptic UTC for the sake of this answer :)

寄居者 2024-12-11 04:35:44

新日期(0) 返回分配一个 Date 对象并将其初始化为表示自称为“纪元”的标准基准时间(即 1970 年 1 月 1 日 00:00:00)以来指定的毫秒数 格林威治标准时间。

因此该值将为 Thu Jan 01 05:30:00 IST 1970

"05:30:00" 取决于您的位置

new Date(0) returns Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

So the value will be Thu Jan 01 05:30:00 IST 1970

"05:30:00" Depens on your location

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文