SimpleDateFormat 在特定日期失败

发布于 2025-01-18 15:27:29 字数 336 浏览 3 评论 0原文

在Java 1.8上,此代码失败了

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
dateFormat.setLenient(false);
dateFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
dateFormat.parse("03/11/2007 02:05:01");

03:05:01正确解析

On java 1.8 this code fails

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
dateFormat.setLenient(false);
dateFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
dateFormat.parse("03/11/2007 02:05:01");

Interesting, that 03:05:01 parses correctly

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

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

发布评论

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

评论(1

只想待在家 2025-01-25 15:27:29

是的,那是因为2007-03-11T02:05:01在美国/new_york时区从未发生过。

The spring-forward daylight saving change occurred at 2007-03-11T07:00:00Z, so anyone watching a time-zone-aware clock would have seen:

  • 01:59:58
  • 01:59:59
  • 03:00:00
  • 03:00:01

You've told the SimpleDateFormat to handle the input strictly, then given it a date/time that didn't exist, so it's reasonable for it to fail.

重要的是,无论您要如何处理这个问题,我都会强烈地鼓励您离开旧版date/日历/code>/dateformat类型,然后使用java.Time

Yes, that's because 2007-03-11T02:05:01 never occurred in the America/New_York time zone.

The spring-forward daylight saving change occurred at 2007-03-11T07:00:00Z, so anyone watching a time-zone-aware clock would have seen:

  • 01:59:58
  • 01:59:59
  • 03:00:00
  • 03:00:01

You've told the SimpleDateFormat to handle the input strictly, then given it a date/time that didn't exist, so it's reasonable for it to fail.

Importantly, regardless of how you want to handle this, I would strongly encourage you to move off the legacy Date/Calendar/DateFormat types, and use java.time instead.

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