Java 8 LocalDateTime 和 DateTimeFormatter

标签 java java-8

下面的代码抛出异常..我在这里做错了什么吗?

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'sy'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 更改为 ddMMuuHHmmssSSSddMMyyHHmmssSSS ,它应该可以正常工作,因为在这种情况下解析器知道在哪里停止完全正确。

关于Java 8 LocalDateTime 和 DateTimeFormatter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36515792/

相关文章:

java - 当使用 Spring 构造函数注入(inject)时,bean 是否在构造函数中完全初始化?

java - 在 Linux (Ubuntu) 中在 java 7 和 java 8 之间切换的推荐方法是什么?

java - 如何删除具有分隔符的字符串中的重复值

java - 如何使图像填充整个按钮JavaFX

java - 无法从 Java Spring 应用程序连接到 MySQL,即使它可以从控制台运行

date - java.time.temporal.UnsupportedTemporalTypeException : Unsupported field: OffsetSeconds

Java Map 合并与 computeIfAbsent 和 computeIfPresent

Java-8:流还是更简单的解决方案?

java - 榛树。序列化失败

java - 将 "\0"添加到子集范围末尾