[英]JSR-310 - parsing seconds fraction with variable length
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?有没有一种方法可以创建 JSR-310 格式化程序,它能够以可变长度的秒数解析以下日期/时间?
2015-05-07 13:20:22.276052
or或者
2015-05-07 13:20:22.276
Example code:示例代码:
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);
This solves the problem: 这解决了这个问题:
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
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). JiriS的答案是不正确的,因为它使用
appendValue
而正确的方法是使用DateTimeFormatterBuilder.appendFraction
(它也处理小数点)。 The difference can be seen in the second system out, where appendValue
incorrectly parses "2015-05-07T13:20:22.000276". 可以在第二个系统中看到差异,其中
appendValue
错误地解析“2015-05-07T13:20:22.000276”。
When parsing, LocalDateTime.parse(str, formatter)
is a neater approach than using the formatter directly in most cases. 在解析时,
LocalDateTime.parse(str, formatter)
比在大多数情况下直接使用格式化程序更简洁。
When using the builder , take advantage of appendPattern()
and optionalStart()
to keep things neat. 使用构建器时 ,请利用
appendPattern()
和optionalStart()
来保持整洁。
And this one works 这一个有效
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();
Parsing fails with a datetime without any ":" characters:解析失败,日期时间没有任何“:”字符:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("yyyyMMddHHmmss")
.appendFraction(ChronoField.MICRO_OF_SECOND, 0, 9, false)
.toFormatter();
System.out.println(LocalDateTime.parse("20150507132022123", formatter));
Edit: it was appendFraction() which expects "."编辑:它是 appendFraction() 期望“。” character.
特点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.