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

后端 未结 2 2084
逝去的感伤
逝去的感伤 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)
    

提交回复
热议问题