[英]What I am doing wrong when parsing an ISO8601 date time?
我期待下面的測試通過。 有人可以告訴我我在這里做錯了什么嗎? 很可能我使用了錯誤的模式,但我看不出有什么問題。
@Test
public void parseDateTest() {
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.sss'Z'");
DateTime dt = formatter.parseDateTime("1983-03-06T05:00:03.000Z");
assertEquals("1983-03-06T05:00:03.000Z", dt.toString());
}
僅供參考 dt.toString() 打印:1983-03-06T05:00:00.000Z
謝謝!
PS 請注意,在此代碼段中,我依賴於默認時區。 這不是生產代碼,許多其他問題都涵蓋了如何根據需要正確處理時區。
默認時區源自系統屬性 user.timezone。 如果它是 null 或不是有效標識符,則轉換 JDK TimeZone 默認值。 如果失敗,則使用 UTC。
這將檢查"1983-03-06T05:00:03.000Z"
是否等於dt.toString()
。 您說dt.toString()
等於"1983-03-06T05:00:00.000Z"
。
"1983-03-06T05:00:03.000Z" !== "1983-03-06T05:00:00.000Z"
現在的問題是為什么dt.toString()
沒有正確的秒數。 讓我們看一下您的DateTimeFormat
模式:
"yyyy-MM-dd'T'HH:mm:ss.sss'Z'"
根據文檔 , s
表示“分鍾的秒數”, S
表示“秒的分數”(請注意情況)。 這意味着在您的輸入字符串中, 03
和000
都被解析為秒(當后者應為小數時),並且DateTime
的秒數被00
覆蓋。 嘗試更新此格式字符串:
@Test
public void parseDateTest() {
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
DateTime dt = formatter.parseDateTime("1983-03-06T05:00:03.000Z");
assertEquals("1983-03-06T05:00:03.000Z", dt.toString());
}
不要使用dt.toString()
,而要使用formatter.format(dt)
。 這就是格式化程序的用途:
@Test
public void parseDateTest() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
LocalDateTime dt = formatter.parse("1983-03-06T05:00:03.000Z", LocalDateTime::from);
assertEquals("1983-03-06T05:00:03.000Z", formatter.format(dt));
}
下面引用來自Joda-Time主頁的通知:
請注意,從 Java SE 8 開始,要求用戶遷移到 java.time (JSR-310) - JDK 的核心部分,它取代了這個項目。
使用java.time
API 的解決方案: java.time
API 基於ISO 8601 ,因此您不需要DateTimeFormatter
來解析已經采用 ISO 8601 格式的日期時間字符串(例如,您的日期時間字符串, 1983-03-06T05:00:03.000Z
)。
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
class Main {
public static void main(String[] args) {
String strModifiedDate = "1983-03-06T05:00:03.000Z";
Instant instant = Instant.parse(strModifiedDate);
System.out.println(instant);
// It can also be directly parsed into a ZonedDateTime
ZonedDateTime zdt = ZonedDateTime.parse(strModifiedDate);
System.out.println(zdt);
// or even into an OffsetDateTime
OffsetDateTime odt = OffsetDateTime.parse(strModifiedDate);
System.out.println(odt);
}
}
Output :
1983-03-06T05:00:03Z
1983-03-06T05:00:03Z
1983-03-06T05:00:03Z
從Trail:Date Time了解有關現代日期時間 API 的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.