Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 DateTimeFormatter dropping millis when they're zero?

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
like image 399
Chris Kessel Avatar asked Feb 03 '16 18:02

Chris Kessel


People also ask

What is the Java time format DateTimeFormatter?

format. DateTimeFormatterBuilder Class in Java. DateTimeFormatterBuilder Class is a builder class that is used to create date-time formatters. DateTimeFormatter is used as a Formatter for printing and parsing date-time objects.

Is Java time DateTimeFormatter thread safe?

DateTimeFormatter is immutable and thread-safe. DateTimeFormatter formats a date-time using user defined format such as "yyyy-MMM-dd hh:mm:ss" or using predefined constants such as ISO_LOCAL_DATE_TIME. A DateTimeFormatter can be created with desired Locale, Chronology, ZoneId, and DecimalStyle.

What is the default format of LocalTime in Java 87?

Java LocalTime class is an immutable class that represents time with a default format of hour-minute-second.

What is ZonedDateTime format?

A date-time with a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30+01:00 Europe/Paris . ZonedDateTime is an immutable representation of a date-time with a time-zone.


1 Answers

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.

like image 69
Jon Skeet Avatar answered Sep 28 '22 08:09

Jon Skeet