我分别用了
SimpleDateFormat
和DateTimeFormatter
来解析:
val text = "Tue, 07 Mar 2023 15:32:23 +0800"
val pattern = "EEE, dd MMM yyyy HH:mm:ss zzz"
val date = SimpleDateFormat(pattern, Locale.ENGLISH).parse(text)
println(date)
val dateTime = LocalDateTime.parse(text, DateTimeFormatter.ofPattern(pattern, Locale.ENGLISH))
println(dateTime)
但是
DateTimeFormatter
报错:
java.time.format.DateTimeParseException:
Text 'Tue, 07 Mar 2023 15:32:23 +0800' could not be parsed at index 26
我知道它可以使用内置类型成功解析
DateTimeFormatter.RFC_1123_DATE_TIME
。
但是我想知道这种模式的问题在哪里?为什么DateTimeFormatter
会出错?
找到一个相关的问题,但是和我的不一样,他的时区是
GMT
,我的是+0800
+0800
不是时区,它是与 UTC 的偏移量。
A
DateTimeFormatter
distingishes between zone (ZoneId
) and offset (ZoneOffset
) and supports different pattern characters that's why it refuses to parse your text
…
我会解析一个
String
,它包含从 UTC 到 OffsetDateTime
的偏移量,而不是 LocalDateTime
,因为后者会剥离有关偏移量的信息,只保留日期和一天中的时间。但这显然取决于具体要求……
这意味着如果你想用
String
解析这个输入 DateTimeFormatter
,你将不得不引入不同的模式。
您可以在该模式中使用
xxxx
代替 zzz
(其余部分保持不变,但最好使用 uuuu
代替 yyyy
)。
fun main() {
// input String
val text = "Tue, 07 Mar 2023 15:32:23 +0800"
// pattern for the SimpleDateFormat
val patternSdf = "EEE, dd MMM yyyy HH:mm:ss zzz"
// pattern for the DateTimeFormatter
val patternDtf = "EEE, dd MMM yyyy HH:mm:ss xxxx"
// get a java.util.Date by parsing the String with the SimpleDateFormat
val date = SimpleDateFormat(patternSdf, Locale.ENGLISH).parse(text)
// print the Date
println(date)
// get a LocalDateTime by parsing the String with the DateTimeFormatter
val dateTime = LocalDateTime.parse(
text,
DateTimeFormatter.ofPattern(patternDtf, Locale.ENGLISH)
)
// print it
println(dateTime);
// get an OffsetDateTime using the same approach
val offsetDateTime = OffsetDateTime.parse(
text,
DateTimeFormatter.ofPattern(patternDtf, Locale.ENGLISH)
)
// print it
println(offsetDateTime)
}
输出:
Tue Mar 07 07:32:23 UTC 2023
2023-03-07T15:32:23
2023-03-07T15:32:23+08:00