JSR-310 - 解析具有可变长度的秒分数

JSR-310 - parsing seconds fraction with variable length

有没有一种方法可以创建 JSR-310 格式化程序,它能够解析以下两个 date/times 具有可变长度的秒分数?

2015-05-07 13:20:22.276052

2015-05-07 13:20:22.276

示例代码:

DateTimeFormatter formatter
= new java.time.format.DateTimeFormatterBuilder()
        .append( java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") )
        .appendOptional( java.time.format.DateTimeFormatter.ofPattern(".SSSSSS") )
        .toFormatter();
formatter.parse("2015-05-07 13:20:22.276052", LocalDateTime::from);

这个有效

DateTimeFormatter formatter
= new java.time.format.DateTimeFormatterBuilder()
        .append( java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") )
        .appendOptional(
                new java.time.format.DateTimeFormatterBuilder()
                    .appendLiteral('.')
                    .appendValue( ChronoField.MICRO_OF_SECOND, 1, 6, SignStyle.NOT_NEGATIVE).toFormatter())
        .toFormatter();

这解决了问题:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .appendPattern("yyyy-MM-dd HH:mm:ss")
    .appendFraction(ChronoField.MICRO_OF_SECOND, 0, 6, true)
    .toFormatter();

System.out.println(LocalDateTime.parse("2015-05-07 13:20:22.276052", formatter));
System.out.println(LocalDateTime.parse("2015-05-07 13:20:22.276", formatter));
System.out.println(LocalDateTime.parse("2015-05-07 13:20:22", formatter));

// output
2015-05-07T13:20:22.276052
2015-05-07T13:20:22.276
2015-05-07T13:20:22

is incorrect, as it uses appendValue whereas the correct way is to use DateTimeFormatterBuilder.appendFraction (which also handles the decimal point). The difference can be seen in the second system out, where appendValue 错误地解析了“2015-05-07T13:20:22.000276”。

解析时,LocalDateTime.parse(str, formatter) 在大多数情况下比直接使用格式化程序更简洁。

使用 builder, take advantage of appendPattern() and optionalStart() 来保持整洁。

解析失败,日期时间没有任何“:”字符:

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendPattern("yyyyMMddHHmmss")
            .appendFraction(ChronoField.MICRO_OF_SECOND, 0, 9, false)
            .toFormatter();
        System.out.println(LocalDateTime.parse("20150507132022123", formatter));

编辑:appendFraction() 需要 "." 个字符。