15

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?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Ed Thomas
  • 1,153
  • 1
  • 12
  • 21
  • Your goal is to just find if the date has millisecond precision? – Sotirios Delimanolis Oct 08 '15 at 21:13
  • 1
    Goal is to format that date with the fractional second part even if those milliseconds are equal to 0. In other words, mimic what Joda does. – Ed Thomas Oct 08 '15 at 21:21
  • 1
    Quick Reminder: java.time provides a resolution of [nanoseconds](https://en.wikipedia.org/wiki/Nanosecond), as opposed to the milliseconds resolution of Joda-Time & java.util.Date. That is means up to nine (9) digits of a fractional second. So if you limit to 3, you may be hiding/losing data. See [this diagram of mine](http://i.stack.imgur.com/OW0RW.png). – Basil Bourque Oct 08 '15 at 22:50

1 Answers1

20

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

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724