Java 8 DateTimeFormatter dropping millis when they're zero?
Asked Answered
M

1

8

This seems weird. Java 8 is formatting the output differently depending on whether the millis is zero. How do you force Java 8 (1.8.0_20) to always spit out the millis regardless of if they're zero or not?

public static void main(String[] args) {
    TemporalAccessor zeroedMillis = DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse("2015-07-14T20:50:00.000Z");
    TemporalAccessor hasMillis = DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse("2015-07-14T20:50:00.333Z");
    System.out.println(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(zeroedMillis));
    System.out.println(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(hasMillis));
}

2015-07-14T20:50:00Z
2015-07-14T20:50:00.333Z
Menswear answered 3/2, 2016 at 18:8 Comment(0)
I
12

You don't use ISO_OFFSET_DATE_TIME, basically :)

If you follow the documentation for that, you end up in the docs of ISO_LOCAL_TIME which has:

This returns an immutable formatter capable of formatting and parsing the ISO-8601 extended local time format. The format consists of:

  • Two digits for the hour-of-day. This is pre-padded by zero to ensure two digits.
  • A colon
  • Two digits for the minute-of-hour. This is pre-padded by zero to ensure two digits.
  • If the second-of-minute is not available then the format is complete.
  • A colon
  • Two digits for the second-of-minute. This is pre-padded by zero to ensure two digits.
  • If the nano-of-second is zero or not available then the format is complete.
  • A decimal point
  • One to nine digits for the nano-of-second. As many digits will be output as required.

If you always want exactly 3 digits, I suspect you want DateTimeFormatter.ofPattern with a pattern of yyyy-MM-dd'T'HH:mm:ss.SSSX.

Inventive answered 3/2, 2016 at 18:18 Comment(9)
Yea, unfortunately, that pattern fails to parse: "could not be parsed at index 23". Searches seem to indicate some sort of bug related to fractional (milli) parsing.Menswear
@Chris: Will have a look when I've finished tea :)Inventive
@ChrisKessel: Hmm... it works for me...that's very odd.Inventive
I'm trying this, what's your code look like? DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse("2016-02-03T10:40:31.457Z"); Error: Text '2016-02-03T10:40:31.457Z' could not be parsed at index 23Menswear
@ChrisKessel: Ah, so it's parsing the value that's the problem. From your previous comment I thought you meant the pattern failed to parse, i.e. that ofPattern failed. Will look into that.Inventive
@ChrisKessel: Fixed it - it needs an X instead of a Z at the end. See the edited answer.Inventive
Thanks! Strange, the same format with the Z worked in joda, so I figured it'd work in java time. I guess their interpretations of the codes are different?Menswear
@Chris: Yup, every API has its own pattern oddities :)Inventive
Let us continue this discussion in chat.Menswear

© 2022 - 2024 — McMap. All rights reserved.