简体   繁体   中英

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.

The ISO 8601 standard allows either a COMMA or a FULL STOP (dot, period) as the decimal mark for a fraction-of-second. The comma is preferred .

But when I try to parse an Instant from an input string containing a comma, a DateTimeParseException is thrown. A similar string with a dot instead succeeds.

What is wrong? How do I parse such standard strings containing a comma?

tl;dr

Only dot works in 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.

In most other ways, the java.time classes offer excellent support for ISO 8601 standard formats. Fortunately this lacking is easily remedied in your own code. Simply replace any comma with a dot when parsing ISO 8601 strings.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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