我有以下程式,看起來 ZonedDateTime 無法決議日期字串。我應該使用不同的日期格式或不同的庫來決議嗎?
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
class Scratch {
public static void main(String[] args) {
final String inputDate = "2022-03-12T03:59:59 0000Z";
ZonedDateTime.parse(inputDate, DateTimeFormatter.ISO_DATE_TIME).toEpochSecond();
}
}
Exception in thread "main" java.time.format.DateTimeParseException: Text '2022-03-12T03:59:59 0000Z' could not be parsed, unparsed text found at index 19
at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2053)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1952)
at java.base/java.time.ZonedDateTime.parse(ZonedDateTime.java:599)
at Scratch.main(scratch_29.java:7)
Process finished with exit code 1
uj5u.com熱心網友回復:
這不是 ISO_DATE_TIME 格式。那將需要類似2022-03-12T03:59:59 0000
(沒有'Z')的東西。一個有效的格式化程式看起來像:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
class Scratch {
public static void main(String[] args) {
final String inputDate = "2022-03-12T03:59:59 0000Z";
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
.optionalStart()
.appendPattern(".SSS")
.optionalEnd()
.optionalStart()
.appendZoneOrOffsetId()
.optionalEnd()
.optionalStart()
.appendOffset(" HHMM", "0000")
.optionalEnd()
.optionalStart()
.appendLiteral('Z')
.optionalEnd()
.toFormatter();
long epochSecond = ZonedDateTime.parse(inputDate, formatter).toEpochSecond();
System.out.println("epochSecond is " epochSecond);
}
}
源自這篇文章。您可以在一個地方創建該格式化程式并再次使用它。
uj5u.com熱心網友回復:
tl;博士
java.time.Instant
您的輸入恰好是該類默認使用的標準 IS0 8601 格式的變體。修復您的輸入字串,然后決議。
Instant.parse( "2022-03-12T03:59:59 0000Z".replace( " 0000Z" , "Z" ) )
或者,重新格式化:
Instant.parse
(
"2022-03-12T03:59:59 0000Z"
.replace( " 0000Z" , "Z" )
)
請參閱在IdeOne.com上實時運行的代碼。
2022-03-12T03:59:59Z
細節
ZonedDateTime
這里不合適
ZonedDateTime
是您輸入的錯誤類。您的輸入有Z
一個標準縮寫,表示與 UTC 零時分秒的偏移量。但沒有指明時區,只是一個偏移量。所以使用OffsetDateTime
orInstant
而不是ZonedDateTime
.
0000
和Z
多余的
這 0000
也意味著零時分秒的偏移量。這與 . 的含義相同Z
。所以這部分是多余的。我建議您對資料的發布者進行有關標準ISO 8601格式的教育。無需發明您輸入中看到的格式。
字串操作而不是自定義格式化程式
如果您的所有輸入都具有相同的結尾 0000Z
,我建議您清理傳入資料而不是定義格式模式。
String input = "2022-03-12T03:59:59 0000Z".replace( " 0000Z" , "Z" ) ;
Instant instant = Instant.parse( input ) ;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/444049.html
標籤:爪哇 约会时间 日期时间格式 日期时间偏移 分区日期时间
下一篇:MySQL日期分組選擇陳述句