从Joda迁移至java.time:DateTimeFormatter多偏移格式输出异常
Joda转java.time格式化重复偏移问题修复
你遇到的问题根源在于DateTimeFormatterBuilder的构造逻辑:你给Formatter加了三个独立的可选偏移格式段,解析时这些可选段会匹配第一个符合的格式,但格式化时只要数据存在,所有可选段都会被输出,导致同一个时区偏移被以+01:00、+0100、+01三种格式重复拼接,就出现了2023-02-08T09:30:00.000+01:00+0100+01的异常结果。
修复方法一:把偏移格式包装成互斥可选块
将三个偏移格式放在同一个optionalStart()/optionalEnd()块内,确保格式化时只输出一种偏移格式,同时保留解析多格式的能力:
@Before public void before() { DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder() .append(DateTimeFormatter.ISO_LOCAL_DATE_TIME) .optionalStart().appendPattern(".SSS").optionalEnd() // 把三个偏移格式包装为同一可选块,实现互斥输出 .optionalStart() .appendOffset("+HH:MM", "+00:00") .optionalStart().appendOffset("+HHMM", "+0000").optionalEnd() .optionalStart().appendOffset("+HH", "Z").optionalEnd() .optionalEnd(); dateTimeFormatter = dateTimeFormatterBuilder.toFormatter(); }
修复方法二:使用appendOffsetId简化实现
appendOffsetId()方法可以自动兼容多种偏移格式的解析,格式化时默认输出标准的+HH:MM格式,代码更简洁:
@Before public void before() { DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder() .append(DateTimeFormatter.ISO_LOCAL_DATE_TIME) .optionalStart().appendPattern(".SSS").optionalEnd() .appendOffsetId(); dateTimeFormatter = dateTimeFormatterBuilder.toFormatter(); }
验证
修改后运行testFormatWithJava()测试,会得到预期的2023-02-08T09:30:00.000+01:00结果,同时原有的解析测试testParseDateStringWithJava()依然能正常解析三种不同偏移格式的日期字符串。
内容的提问来源于stack exchange,提问作者kevin h
相关产品推荐
相关产品推荐

