问题
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)
回答1:
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.
From JavaDoc of Year:
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.
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.
来源:https://stackoverflow.com/questions/36515792/java-8-localdatetime-and-datetimeformatter