Florent Florent - 1 year ago 212
Java Question

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

I'm trying to cleanup a mix of various code around datetime management to only Java 8

namespace. Right now I have a small issue with the default
. The
formatter only shows milliseconds when they are not equal to zero.

The epoch is rendered as
instead of

I made a unit test to explain the problem and how we need to final dates to be compared one to each other.

public void java8Date() {
DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
String epoch, almostEpoch, afterEpoch;

{ // before epoch
java.time.Instant instant = java.time.Instant.ofEpochMilli(-1);
almostEpoch = formatter.format(instant);
assertEquals("1969-12-31T23:59:59.999Z", almostEpoch );

{ // epoch
java.time.Instant instant = java.time.Instant.ofEpochMilli(0);
epoch = formatter.format(instant);
// This fails, I get 1970-01-01T00:00:00Z instead
assertEquals("1970-01-01T00:00:00.000Z", epoch );

{ // after epoch
java.time.Instant instant = java.time.Instant.ofEpochMilli(1);
afterEpoch = formatter.format(instant);
assertEquals("1970-01-01T00:00:00.001Z", afterEpoch );

// The end game is to make sure this rule is respected (this is how we order things in dynamo):
assertTrue(epoch.compareTo(almostEpoch) > 0);
assertTrue(afterEpoch.compareTo(epoch) > 0); // <-- This assert would also fail if the second assert fails

Answer Source

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

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

I hope it works all scenarios, don't hesitate to add a better/cleaner answer.

I hope that can help someone else.

Just to explain where it comes from:

ISO_INSTANT is defined like this:

public static final DateTimeFormatter ISO_INSTANT;
static {
    ISO_INSTANT = new DateTimeFormatterBuilder()
            .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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download