java.time.DateTimeFormatter : Need ISO_INSTANT that always renders milliseconds

后端 未结 2 2086
逝去的感伤
逝去的感伤 2021-02-07 03:55

I\'m trying to cleanup a mix of various code around datetime management to only Java 8 java.time namespace. Right now I have a small issue with the default DateTimeFormatter for

相关标签:
2条回答
  • 2021-02-07 04:21

    OK, I looked at the the source code and it's pretty straightforward:

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

    I hope it works for all scenarios, and it can help someone else. Don't hesitate to add a better/cleaner answer.

    Just to explain where it comes from, in the JDK's code,

    ISO_INSTANT is defined like this:

    public static final DateTimeFormatter ISO_INSTANT;
    static {
        ISO_INSTANT = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .appendInstant()
                .toFormatter(ResolverStyle.STRICT, null);
    }
    

    And DateTimeFormatterBuilder::appendInstant is declared as:

    public DateTimeFormatterBuilder appendInstant() {
        appendInternal(new InstantPrinterParser(-2));
        return this;
    }
    

    And the constructor InstantPrinterParser signature is:

    InstantPrinterParser(int fractionalDigits)
    
    0 讨论(0)
  • 2021-02-07 04:37

    The accepted Answer by Florent is correct and good.

    I just want to add some clarification.

    The mentioned formatter, DateTimeFormatter.ISO_INSTANT, is default only for the Instant class. Other classes such as OffsetDateTime and ZonedDateTime may use other formatters by default.

    The java.time classes offer a resolution up to nanosecond, much finer granularity than milliseconds. That means up to 9 digits in the decimal fraction rather than merely 3 digits.

    The behavior of DateTimeFormatter.ISO_INSTANT varies by the number of digits in the decimal fraction. As the doc says (emphasis mine):

    When formatting, the second-of-minute is always output. The nano-of-second outputs zero, three, six or nine digits as necessary.

    So depending on the data value contained within the Instant object, you may see any of these outputs:

    2011-12-03T10:15:30Z

    2011-12-03T10:15:30.100Z

    2011-12-03T10:15:30.120Z

    2011-12-03T10:15:30.123Z

    2011-12-03T10:15:30.123400Z

    2011-12-03T10:15:30.123456Z

    2011-12-03T10:15:30.123456780Z

    2011-12-03T10:15:30.123456789Z

    The Instant class is meant to be the basic building block of java.time. Use it frequently for data passing, data storage, and data exchange. When generating String representations of the data for presentation to users, use OffsetDateTime or ZonedDateTime.

    0 讨论(0)
提交回复
热议问题