我正在尝试将日期时间管理中的各种代码混合到仅Java 8java.time
名称空间。现在我有一个小问题用默认DateTimeFormatter
的Instant
。该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)));
}
}
好的,我查看了源代码,它非常简单:
DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendInstant(3).toFormatter();
我希望它适用于所有情况,并且可以帮助其他人。不要犹豫,添加一个更好/更干净的答案。
只是为了说明它的来源,在JDK的代码中,
ISO_INSTANT
定义如下:
public static final DateTimeFormatter ISO_INSTANT;
static {
ISO_INSTANT = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendInstant()
.toFormatter(ResolverStyle.STRICT, null);
}
并DateTimeFormatterBuilder::appendInstant
声明为:
public DateTimeFormatterBuilder appendInstant() {
appendInternal(new InstantPrinterParser(-2));
return this;
}
构造函数的InstantPrinterParser
签名是:
InstantPrinterParser(int fractionalDigits)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句