प्रस्तुत करता है मैं डेटाटाइम प्रबंधन के आसपास विभिन्न कोड का मिश्रण केवल जावा 8 java.time
नामस्थान में साफ़ करने की कोशिश कर रहा हूं। अभी Instant
के लिए डिफ़ॉल्ट DateTimeFormatter
के साथ मेरा एक छोटा सा मुद्दा है। DateTimeFormatter.ISO_INSTANT
फ़ॉर्मेटर केवल मिलीसेकंड दिखाता है जब वे शून्य के बराबर नहीं होते हैं।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)));
}
}
डिफ़ॉल्ट प्रारूप केवल शून्य से अलग होने पर नैनोसेकंड प्रस्तुत करेगा। यदि आप हमेशा मिलीसेकंड (और कभी नैनोसेकंड नहीं) चाहते हैं, तो क्यों न केवल कस्टम फॉर्मेटर का उपयोग करें, जैसे 'डेटटाइमफॉर्मेटर फॉर्मेटर = डेटटाइमफॉर्मेटर.ओपटरर्न ("yyyy-MM-dd'T'HH: mm: ss.SSSX") .ZZone (ZoneId .of ("यूटीसी")); '? – mihi
मैं 'त्वरित :: toString() 'के लिए उपयोग किए गए फ़ॉर्मेटर के जितना संभव हो उतना करीब रहना चाहता था। शायद मुझे वास्तव में एक स्ट्रिंग पैटर्न का उपयोग करना चाहिए था। – Florent