Java 8 LocalDateTime and DateTimeFormatter

落花浮王杯 提交于 2021-02-08 04:49:33

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!