You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

XMLGregorianCalendar转ISO_8601遇解析异常,求解决方案

问题解决思路与代码修正

异常原因

Instant.parse()仅支持严格符合ISO-8601的带时区标识(如Z)的日期格式,而你的输入2022-11-23T13:53:31既无时区信息,也无毫秒部分,因此触发解析异常。

解决方案

需要分两步处理:

  1. 先将无时区、无毫秒的日期字符串解析为LocalDateTime
  2. 补充时区(设为UTC,对应Z)和毫秒值(可指定固定值或设为0),再转换为Instant用于后续日期比较

修正后的代码

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public static boolean checkIfDateMatches(String fromDate, String toDate, String inputDate) throws Exception {
    // 定义兼容两种格式的解析器:支持带/不带毫秒、带/不带Z的ISO格式
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[.SSS][X]");
    
    // 解析输入日期为LocalDateTime,再转为UTC时区的Instant
    LocalDateTime inputLocal = LocalDateTime.parse(inputDate, formatter);
    Instant inputInstant = inputLocal.atZone(ZoneId.of("UTC")).toInstant();
    
    // 解析起止日期(假设fromDate/toDate是带Z的格式,直接用Instant.parse即可)
    Instant startInstant = Instant.parse(fromDate);
    Instant endInstant = Instant.parse(toDate);
    
    // 日期比较
    return inputInstant.compareTo(startInstant) >= 0 && inputInstant.compareTo(endInstant) <= 0;
}

// 如果需要将原日期格式转换为目标格式(2022-11-23T13:53:31.890Z),可使用以下方法
public static String convertToTargetFormat(String originalDate) {
    DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
    LocalDateTime localDateTime = LocalDateTime.parse(originalDate, inputFormatter);
    // 这里指定毫秒为890,也可以根据需求设为0或其他值
    LocalDateTime withMillis = localDateTime.withNano(890 * 1000000);
    return withMillis.atZone(ZoneId.of("UTC")).format(DateTimeFormatter.ISO_INSTANT);
}

代码说明

  • DateTimeFormatter的[.SSS][X]表示可选的毫秒部分和时区标识,兼容你的两种日期格式
  • 将LocalDateTime转为UTC时区的Instant,确保与目标格式的时区一致(目标格式的Z代表UTC)
  • 转换目标格式时,通过withNano设置毫秒值(1毫秒=1000000纳秒),再用ISO_INSTANT格式化输出标准带Z的ISO格式

内容的提问来源于stack exchange,提问作者Sikandar Sahab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 02:30:44