下面的代码抛出异常..我在这里做错了什么吗?
DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(
"ddMMuuuuHHmmssSSS"
);
String currentTime=FORMATTER.format(LocalDateTime.now());
System.out.println(currentTime);
LocalDateTime parsedTime=LocalDateTime.parse(currentTime,FORMATTER);
09042016161444380
Exception in thread "main" java.time.format.DateTimeParseException: Text '09042016161444380' could not be parsed at index 4
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
最佳答案
如Jon Skeet在上面的评论中提到,使用 uuuu
解析器不知道这一年将在哪里停止。这是因为解析器按字面解释了超过 2 个 u's
或 y's
。
摘自年份
的JavaDoc:
For parsing, if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits. So using the pattern "MM/dd/yyyy", "01/11/12" parses to Jan 11, 12 A.D.
因此,如果您将其从 ddMMuuuHHmmssSSS
更改为 ddMMuuHHmmssSSS
或 ddMMyyHHmmssSSS
,它应该可以正常工作,因为在这种情况下解析器知道在哪里停止完全正确。
关于Java 8 LocalDateTime 和 DateTimeFormatter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36515792/