datetime 관리와 관련된 다양한 코드를 Java 8 java.time
네임 스페이스로 정리하려고합니다. 지금은 의 작은 문제 (Instant
)가 있습니다. DateTimeFormatter.ISO_INSTANT
포맷터는 0이 아닌 경우에만 밀리 초를 표시합니다.java.time.DateTimeFormatter : 항상 밀리 초를 렌더링하는 ISO_INSTANT가 필요합니다.
신기원은 1970-01-01T00:00:00.000Z
대신에 1970-01-01T00:00:00Z
으로 렌더링됩니다.
나는이 문제를 설명하기 위해 단위 테스트를 실시했으며 서로 비교할 최종 날짜를 어떻게 필요로 하는지를 설명했습니다.
@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)));
}
}
기본 형식은 0과 다른 경우에만 나노초도 렌더링합니다. 밀리 세컨드 (그리고 결코 나노초가 아닌)를 원할 경우,'DateTimeFormatter formatter = DateTimeFormatter.ofPattern ("yyyy-MM-dd'T'HH : mm : ss.SSSX")와 같은 커스텀 포맷터를 사용하면 안된다 .Zone (ZoneId . ("UTC")); – mihi
'Instant :: toString()'에 사용 된 포맷터에 최대한 가까이 있기를 원했습니다. 어쩌면 나는 실제로 문자열 패턴을 사용해야 만했을 것입니다. – Florent