JSR-310 - 解析具有可变长度的秒分数 [英] JSR-310 - parsing seconds fraction with variable length

查看:97
本文介绍了JSR-310 - 解析具有可变长度的秒分数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法如何创建JSR-310格式化程序,能够用可变长度的秒分数解析以下日期/时间?

Is there a way how to create JSR-310 formatter that is able to parse both following date/times with variable length of seconds fraction?

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 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

JiriS的回答不正确,因为它使用 appendValue 而正确的方法是使用 DateTimeFormatterBuilder.appendFraction (也处理小数点)。可以在第二个系统中看到差异,其中 appendValue 错误解析2015-05-07T13 :20:22.000276。

The answer by JiriS 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 incorrectly parses "2015-05-07T13:20:22.000276".

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

When parsing, LocalDateTime.parse(str, formatter) is a neater approach than using the formatter directly in most cases.

使用构建器,利用 appendPattern() optionalStart() 以保持整洁。

When using the builder, take advantage of appendPattern() and optionalStart() to keep things neat.

这篇关于JSR-310 - 解析具有可变长度的秒分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆