Java用GMT字符串解析字符串中的日期
我有以下日期字符串Tue Feb 04 2020 16:11:25 GMT+0200 (IST)
,我试图使用以下代码将其转换为日期时间:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM d yyyy HH:mm:ss O (zzz)", Locale.ENGLISH);
LocalDate dateTime = LocalDate.parse("Tue Feb 04 2020 16:11:25 GMT+0200 (IST)", formatter);
我得到了以下例外:
Text Tue Feb 04 2020 16:11:25 GMT+0200 (IST) could not be parsed at index 28
我看了下面的问题Java string to date conversion,我明白了
O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00;
那我为什么会有例外呢
# 1 楼答案
2件事-分区DateTime&;0缺少“:”
# 2 楼答案
不要对时区使用固定文本:
不要对现有答案中提到的时区使用固定文本(例如
'GMT'
),因为这种方法可能无法适用于其他地区建议的解决方案是:
输出:
ONLINE DEMO
从Trail: Date Time了解有关现代日期时间API的更多信息
# 3 楼答案
以下模式有效
可以用
x
或X
替换Z
以获得相同的结果如果你愿意,你可以把它拼出来,但这不是必须的
您应该将该输入解析为
OffsetDateTime
,因为输入字符串包括日期、时间、和偏移量输出