DST更改导致java.text.ParseException:无法解析的日期 [英] DST changes caused an java.text.ParseException: Unparseable date
问题描述
以下是引发异常的代码段:
Following is the code snippet which is throwing an exception:
SimpleDateformat dateFormatter = new SimpleDateFormat("yyyyMMddHHmm");
Date date = dateFormatter.parse("201710010200");
上面的代码对凌晨2:00之后的所有日期均抛出异常。一直运行到凌晨01:30
The code above threw exception for all the dates after 2:00 A.M. It ran well till 01:30 A.M.
已配置了夏令时(我使用的是澳大利亚/悉尼
时区)。
DayLight saving time was configured (I'm using Australia/Sydney
timezone).
之后,我可以看到凌晨3:00的日志
凌晨2:00之间的时间和凌晨3:00
After that, I could see logs of 3:00 A.M. Time between 2:00 A.M. and 3:00 A.M. is not logged too.
日志:
01 Oct 03:02: 01错误:无法解析的日期: 201710010200
01 Oct 03:02:01 ERROR : Unparseable date: "201710010200"
原因:java.text.ParseException:无法解析的日期: 201710010200
在java.text.DateFormat.parse(DateFormat.java:357)
Caused by: java.text.ParseException: Unparseable date: "201710010200" at java.text.DateFormat.parse(DateFormat.java:357)
解决了日期字符串 201710010200
无法解析,并指定了正确的日期格式的问题?
What could be the fix of the problem of the date string "201710010200"
not getting parsed, with the right date format specified?
推荐答案
您正在尝试解析未发生的日期/时间。
You're trying to parse a date/time that didn't occur.
我们现在知道这是在悉尼时区。 2017年10月1日在悉尼,凌晨2点钟。如果您每分钟查看一次时钟,则会看到:
We now know that this was in the Sydney time zone. At 2am on October 1st 2017 in Sydney, the clocks went forward to 3am. If you were looking at a clock every minute you'd see:
- 01:58
- 01:59
- 03:00
- 03:01
- 01:58
- 01:59
- 03:00
- 03:01
因此,在该时区根本没有发生凌晨2点(含)到凌晨3点(不含)之间的任何日期/时间。我们不知道是什么导致了您要解析的值,但是:
So any date/time between 2am (inclusive) and 3am (exclusive) simply didn't occur in that time zone. We don't know what produced the values you're trying to parse, but:
- 如果它们是时间戳,那几乎可以肯定最好同时格式化和解析UTC。如果产生它们的时区对于将来的分析很重要,则与UTC保持偏移,并可能与时区ID保持偏移。
- 如果它们是未链接的日期/时间值到任何特定时区,请不要将它们解析为在时区。理想情况下,使用Java 8的
java.time
包并将其解析为LocalDateTime
值
- If they're timestamps, it would almost certainly be better to both format and parse in UTC. Keep an offset from UTC and potentially a time zone ID if the time zone in which they were produced is important for future analysis.
- If they're date/time values which aren't linked to any particular time zone, don't parse them as if they were in a time zone. Ideally, use Java 8's
java.time
package and parse them asLocalDateTime
values
这篇关于DST更改导致java.text.ParseException:无法解析的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!