gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 19:42:43 24 4
gpt4 key购买 nike

我正在尝试将围绕日期时间管理的各种代码混合清理到仅 Java 8 java.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();

我希望它适用于所有场景,并且它可以帮助到其他人。不要犹豫,添加更好/更清晰的答案。

只是为了解释它的来源,in the JDK's code ,

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)

关于java.time.DateTimeFormatter : Need ISO_INSTANT that always renders milliseconds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38042134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com