java.time ISO date format with fixed millis digits

2019-04-04 10:25发布

问题:

By default, the toString method of Instant uses the DateTimeFormatter.ISO_INSTANT formatter. That formatter won’t print the digits for fraction-of-second if they happen to be 0.

java-time examples:

    2015-10-08T17:13:07.589Z
    2015-10-08T17:13:07Z

Joda-Time examples (and what I'd expect from java.time):

    2015-10-08T17:13:07.589Z
    2015-10-08T17:13:07.000Z

This is really frustrating to parse in some systems. Elasticsearch was the first problem I encountered, there's no pre-defined format that supports optional millis, but I can probably work around that with a custom format. The default just seems wrong.

It appears that you can’t really build your own format string for Instants anyway. Is the only option implementing my own java.time.format.DateTimeFormatterBuilder.InstantPrinterParser?

回答1:

Just create a DateTimeFormatter that keeps three fractional digits.

DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendInstant(3).toFormatter();

Then use it. For example:

System.out.println(formatter.format(Instant.now()));
System.out.println(formatter.format(Instant.now().truncatedTo(ChronoUnit.SECONDS)));

…prints (at the time I run it):

2015-10-08T21:26:16.571Z
2015-10-08T21:26:16.000Z

Excerpt of the class doc:

… The fractionalDigits parameter allows the output of the fractional second to be controlled. Specifying zero will cause no fractional digits to be output. From 1 to 9 will output an increasing number of digits, using zero right-padding if necessary. The special value -1 is used to output as many digits as necessary to avoid any trailing zeroes. …