java.time.DateTimeFormatter:需要始终呈现毫秒的ISO_INSTANT
我正在尝试清理有关日期时间管理的各种代码的混合,以仅将Java 8 java.time
命名空间。现在,我对Outstant
的默认DateTimeFormatter
有一个小问题。DateTimeFormatter.ISO_INSTANT
格式化程序仅在毫秒不等于零时才显示毫秒。
纪元呈现为 而不是 。1970-01-01T00:00:00Z
1970-01-01T00:00:00.000Z
我做了一个单元测试来解释这个问题,以及我们需要如何将最终日期相互比较。
@Test
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
{ // to confirm we're not showing nanos
assertEquals("1970-01-01T00:00:00.000Z", formatter.format(Instant.EPOCH.plusNanos(1)));
assertEquals("1970-01-01T00:00:00.001Z", formatter.format(Instant.EPOCH.plusNanos(1000000)));
}
}