解析2023-06-12T10:49:010Z格式日期报错,如何判断是否小于当前日期2天?
日期解析异常的解决方法
问题场景
尝试解析格式为2023-06-12T10:49:010Z的日期时间,判断其是否距离当前日期不足2天,运行时抛出如下解析异常:
Text '2023-06-12T10:49:010Z' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {HourOfDay=10, MinuteOfHour=49, NanoOfSecond=10000000},ISO resolved to 2023-06-12 of type java.time.format.Parsed
使用的代码如下:
public boolean compareDates(){ String givenDate = "2023-06-12T10:49:010Z"; DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:SSS'Z'"); ZonedDateTime givenDateTime = ZonedDateTime.parse(givenDate, dateTimeFormatter); ZonedDateTime currentDateTime = ZonedDateTime.now(); long daysDiffernce = ChronoUnit.DAYS.between(currentDateTime, givenDateTime); return daysDiffernce < 2; }
问题原因
你的怀疑是对的,问题出在两点:
- 格式串中用
SSS匹配毫秒,但原字符串里的010是三位数字表示的秒值(即10秒),而非毫秒,导致解析器错误识别时间分量,缺失秒的核心信息。 - 格式串中用单引号包裹
'Z',会将其当作普通字符处理,无法识别为UTC时区标识,而ZonedDateTime必须依赖时区信息才能完成实例化,因此抛出异常。
解决方案
修正格式串,正确匹配秒和时区,并建议统一用UTC时间做比较避免时区差异:
public boolean compareDates(){ String givenDate = "2023-06-12T10:49:010Z"; // sss匹配三位秒,X匹配UTC时区标识Z DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:sssX"); ZonedDateTime givenDateTime = ZonedDateTime.parse(givenDate, dateTimeFormatter); // 使用UTC时间作为当前时间,避免本地时区干扰 ZonedDateTime currentDateTime = ZonedDateTime.now(ZoneOffset.UTC); long daysDifference = ChronoUnit.DAYS.between(currentDateTime, givenDateTime); return daysDifference < 2; }
补充说明
sss用于匹配三位数字的秒值,支持前补零的情况(如010对应10秒);X用于匹配时区偏移标识,Z会被正确识别为UTC时区;- 比较日期时使用UTC时间,能避免不同本地时区带来的时间差误差,保证比较结果准确。
内容的提问来源于stack exchange,提问作者Girish
相关产品推荐
相关产品推荐

