我应该如何将Instant
转换为带小数点的Unix时间戳字符串以获得亚秒级精度?
测试用例如下:
@Test
public void toStringUnixTime() throws Exception {
assertEquals("0", TimeUtils.toStringUnixTime(Instant.EPOCH));
assertEquals("1491327940.619", TimeUtils.toStringUnixTime(Instant.ofEpochMilli(1491327940619L)));
assertEquals("1491327940.000012345", TimeUtils.toStringUnixTime(Instant.ofEpochSecond(1491327940, 12345)));
}
无法正常工作的提案(总是有尾随的0,总是有小数点)
public static String toStringUnixTime(Instant i){
return i.getEpochSecond() + "." + String.format("%09d", i.getNano());
}
TemporalAccessor
上(比如 LocalDate)都会失败,但只有在运行时才会失败(编译可以通过)?难道静态方法的方式不是更安全吗? - PhilippInstant.from()
可以转换的类型上工作,例如ZonedDateTime
和OffsetDateTime
。但是,像LocalDate
这样的其他情况下它将失败。取决于您认为什么是重要的。 - JodaStephen