将字符串转换为ZonedDateTime时遇DateTimeParseException异常求助
解决ZonedDateTime解析自定义格式字符串的异常问题
你遇到的DateTimeParseException是因为ZonedDateTime.parse()默认使用ISO 8601标准格式(比如2018-03-21T08:00:00+03:30[IRST])来解析时间字符串,但你的输入是自定义的非标准格式,必须手动创建匹配的DateTimeFormatter才能正确解析。
解决方案步骤
拆解你的时间字符串格式
先把你的输入字符串拆成对应格式符:Wed→ 英文星期缩写 →EEEMar→ 英文月份缩写 →MMM21→ 日 →dd2018→ 年 →yyyy08:00:00→ 时分秒 →HH:mm:ssGMT→ 固定字面量 → 用单引号包裹'GMT'(表示这是固定文本,不是格式符)0330→ 不带冒号的时区偏移(±HHmm格式) →xx(IRST)→ 括号包裹的时区ID →'('VV')'(VV用来匹配时区代码)
编写可运行的解析代码
构建自定义DateTimeFormatter时,必须指定Locale.ENGLISH,否则如果系统默认语言不是英文,解析英文星期/月份缩写会失败:
import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Locale; public class TimeParser { public static void main(String[] args) { String startTime = "Wed Mar 21 2018 08:00:00 GMT 0330 (IRST)"; String endTime = "Fri Mar 23 2018 08:00:00 GMT 0430 (IRDT)"; // 定义匹配你输入格式的格式化器 DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern( "EEE MMM dd yyyy HH:mm:ss 'GMT' xx '('VV')'", Locale.ENGLISH ); // 使用自定义格式化器解析字符串 ZonedDateTime startTimeDate = ZonedDateTime.parse(startTime, customFormatter); ZonedDateTime endTimeDate = ZonedDateTime.parse(endTime, customFormatter); // 打印验证结果 System.out.println("解析后的开始时间:" + startTimeDate); System.out.println("解析后的结束时间:" + endTimeDate); } }
额外说明
- 如果你的时区偏移是带冒号的格式(比如
+03:30),把格式符里的xx改成XXX即可; VV格式符支持匹配多种时区标识,包括IRST/IRDT这类缩写,也支持Asia/Tehran这类完整时区ID;- 显式指定
Locale.ENGLISH是关键,避免因系统语言环境差异导致解析失败。
内容的提问来源于stack exchange,提问作者batnight
相关产品推荐
相关产品推荐

