我正在使用jiraapi,在其中一個請求中,我得到了日期欄位的回應,格式如下:2022-10-26T09:34:00.000 0000。我需要將其轉換為LocalDate但我不知道如何使用這種奇怪的格式進行轉換。以下是我已經嘗試過的一些格式:
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
DateTimeFormatter.ISO_LOCAL_DATE_TIME
但是兩者都不能 在日期結束時反序列化這個標志。
Text '2022-10-27T09:34:00.000 0000' could not be parsed, unparsed text found at index 24
uj5u.com熱心網友回復:
您必須添加時區:
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
查看檔案 https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
uj5u.com熱心網友回復:
錯誤訊息告訴您您無法DateTimeFormatter決議. 那是因為 a只是不期望偏移量,它應該只決議 0000StringDateTimeFormatter.ISO_LOCAL_DATE_TIME
- 年
- 一年中的月份
- 一個月中的某一天
- 一天中的小時
- 小時的分鐘
- 分秒
- 秒的分數(和納米)
而已!沒有抵消!沒有區!.
但這也意味著它可以完美地決議所有內容,直到您的示例中出現此偏移為止!
但是,String它幾乎被格式化為OffsetDateTime,但不幸的是,它的 ISO 格式化程式需要一個偏移量,其中小時和分鐘由冒號分隔,例如 00:00,而您String沒有。
java.time授予您基于現有格式器構建自定義格式器的可能性。這就是為什么我在上面提到除了偏移量之外的所有內容都可以用DateTimeFormatter.ISO_LOCAL_DATE_TIME. 您可以采用那個并附加一個 offset-x 模式,然后決議您未分離的偏移量。讓我們稱之為擴展現有格式化程式,這是一個例子:
public static void main(String[] args) {
// your example String
String someTimes = "2022-10-26T09:34:00.000 0000";
// build a suitable formatter by extending an ISO-formatter
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
.appendPattern("xxxx")
.toFormatter(Locale.ENGLISH);
// then parse
LocalDate localDate = LocalDate.parse(someTimes, dtf);
// and print
System.out.println(localDate);
}
輸出:
2022-10-26
創建帶有 a 的格式化程式始終是一個好主意Locale,但在大多數情況下,只決議數值,不帶的格式化程式Locale可能就足夠了。這DateTimeFormatter.ofPattern(String, Locale)也很重要。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/535159.html
標籤:爪哇日期java时间
