Java 8 LocalDateTime和DateTimeFormatter [英] Java 8 LocalDateTime and DateTimeFormatter
问题描述
在下面的一段代码中解决了异常..我在这里做错什么了吗?
below piece of code thorws exception..am i doing something wrong here?
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
.
As Jon Skeet mentioned in the above comment, with uuuu
the parser doesn't know where the year is going to stop. This is because more than 2 u's
or y's
are interpreted literally by the parser.
来自Year
的JavaDoc:
From JavaDoc of Year
:
对于解析,如果模式字母的数量大于2,则将按字面意义解释年份,而不考虑数字的数量.因此,使用模式"MM/dd/yyyy","01/11/12"解析为公元1月11日
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.
因此,如果将其从ddMMuuuuHHmmssSSS
更改为ddMMuuHHmmssSSS
或ddMMyyHHmmssSSS
,它应该可以正常工作,因为在这种情况下,解析器知道确切的停止位置.
Hence, it should work fine if you change it to ddMMuuHHmmssSSS
or ddMMyyHHmmssSSS
from ddMMuuuuHHmmssSSS
as in this instance the parser knows where to stop exactly.
这篇关于Java 8 LocalDateTime和DateTimeFormatter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!