简体   繁体   English

逗号无法通过java.time.Instant解析

[英]Comma fails parsing by java.time.Instant

This fails: 这将失败:

Instant.parse( "2007-12-03T10:15:30,978Z" )  // Fails with comma

while this succeeds: 虽然成功了:

Instant.parse( "2007-12-03T10:15:30.978Z" )  // Succeeds with dot

The java.time classes use standard ISO 8601 formats by default when parsing or generating String representations of date-time values. 解析或生成日期时间值的字符串表示形式时,默认情况下, java.time类使用标准的ISO 8601格式。

The ISO 8601 standard allows either a COMMA or a FULL STOP (dot, period) as the decimal mark for a fraction-of-second. ISO 8601标准允许使用一个COMMAFULL STOP (点,期间)作为十进制标记为几分之一秒。 The comma is preferred . 逗号是首选

But when I try to parse an Instant from an input string containing a comma, a DateTimeParseException is thrown. 但是,当我尝试从包含逗号的输入字符串中解析 Instant ,会引发DateTimeParseException A similar string with a dot instead succeeds. 相反,带有点的类似字符串会成功。

What is wrong? 怎么了? How do I parse such standard strings containing a comma? 如何解析此类包含逗号的标准字符串?

tl;dr tl; dr

Only dot works in java.time. 在Java.time中,只有点有效。 Just replace comma with dot. 只需用点替换逗号。

"2007-12-03T10:15:30,978Z".replace( "," , "." )

Only dot supported, not comma 仅支持点,不支持逗号

In Java 8, the java.time classes expect only a FULL STOP (dot, period) character as the decimal mark. 在Java 8中,java.time类只期望FULL STOP(点,句点)字符作为小数点。

In most other ways, the java.time classes offer excellent support for ISO 8601 standard formats. 在大多数其他方式中,java.time类为ISO 8601标准格式提供了出色的支持。 Fortunately this lacking is easily remedied in your own code. 幸运的是,这种不足很容易在您自己的代码中得到纠正。 Simply replace any comma with a dot when parsing ISO 8601 strings. 解析ISO 8601字符串时,只需将任何逗号替换为一个点即可。

String input = "2007-12-03T10:15:30,978Z" ;
Instant instant = Instant.parse( input.replace( "," , "." ) );

Do the reverse to output a String using the preferred comma rather dot. 进行相反的操作以使用首选逗号而不是点来输出String。 Beware that some protocols and libraries may be biased toward either character. 请注意,某些协议和库可能偏向任一字符。

String output = instant.toString().replace( "." , "," ) ;

For more detailed discussion, see the Question DateTimeFormatter to handle either a FULL STOP or COMMA in fractional second and the issue page for JDK-8132536 有关更多详细的讨论,请参阅问题DateTimeFormatter以在小数秒内处理FULL STOP或COMMA,以及JDK-8132536的问题页面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM