ISO 8601 是標準的日期時間表示法 [1],在一些有遵守標準的網站上,很容易看到這種以表示法表示的時間。
在 Java 裡,有一些不算困難的方法,可以把 ISO-8601 表示法的文字轉成對應的 Epoch Time
然後當然因為有了 Epoch Time,就可以進一步轉成 Calendar 或者 Date 等其他日期相關的類別。
1 2 3 4 5 6 7 8 9 10 11 12 |
DateTimeFormatter datetimeFormatter = new DateTimeFormatterBuilder() .appendOptional(DateTimeFormatter.ofPattern( "yyyy-MM-dd'T'HH:mm:ssZ" )) .toFormatter(); try { // Try to parse the given date time string. Instant instant = Instant.from(datetimeFormatter.parse( "2016-05-31T03:45:58.251Z" )); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(instant.toEpochMilli()); } catch (DateTimeParseException e) { e.printStackTrace(); } |
如果想要驗證結果的話,可以簡單地用像是 JUnit 的方式去確認。
1 2 3 4 5 6 7 8 |
// Set the time zone to GMT. cal.setTimeZone(TimeZone.getTimeZone( "1200" )); Assert.assertEquals( 2016 , cal.get(Calendar.YEAR)); Assert.assertEquals( 4 , cal.get(Calendar.MONTH)); Assert.assertEquals( 31 , cal.get(Calendar.DAY_OF_MONTH)); Assert.assertEquals( 3 , cal.get(Calendar.HOUR_OF_DAY)); Assert.assertEquals( 45 , cal.get(Calendar.MINUTE)); Assert.assertEquals( 58 , cal.get(Calendar.SECOND)); |
所以必須先指定 Calendar 使用格林威治的時區(+0),檢驗才會正確。
參考資料:
沒有留言:
張貼留言