Java中DateTimeFormatter无法识别MESZ时区,求适配的格式化模式
解决MESZ时区标识解析失败的问题
核心问题说明
LocalDateTime本身不包含时区信息,用来解析带时区标识的字符串本身就不合适,应该使用ZonedDateTime或OffsetDateTime这类支持时区的日期时间类。另外,MESZ是中欧夏令时的德语缩写,默认的DateTimeFormatter可能因为Locale不匹配无法识别该标识。
解决方案1:指定德语Locale并使用ZonedDateTime
通过指定德语Locale(Locale.GERMANY),让DateTimeFormatter能够识别德语区的时区缩写,同时改用ZonedDateTime解析:
ZonedDateTime time = ZonedDateTime.parse( "27. April 2021 00:03:50 MESZ", DateTimeFormatter.ofPattern("dd. MMMM yyyy HH:mm:ss z", Locale.GERMANY) );
解决方案2:手动注册时区别名
如果上述方法仍无法识别,可以通过DateTimeFormatterBuilder手动为对应时区偏移量添加别名:
// MESZ对应UTC+2(7200秒),MEZ对应UTC+1(3600秒) DateTimeFormatter formatter = new DateTimeFormatterBuilder() .appendPattern("dd. MMMM yyyy HH:mm:ss ") .appendText(ChronoField.OFFSET_SECONDS, Map.of( 7200, "MESZ", 3600, "MEZ" )) .toFormatter(Locale.GERMANY); ZonedDateTime time = ZonedDateTime.parse("27. April 2021 00:03:50 MESZ", formatter);
内容的提问来源于stack exchange,提问作者Vishal
相关产品推荐
相关产品推荐

