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

如何解决Java解析2021-09-02T13:16:00.0000000Z日期的ParseException报错

问题原因与解决方案

现有代码的错误点

  • 字符串替换逻辑无效:你对入参做了replaceFirst替换T字符,但后续调用formatter.parse()时传入的是未处理的原publishedDate,替换操作完全没有生效
  • 小时制格式符错误:hh代表12小时制,你提供的日期中小时为13属于24小时制,应使用HH作为小时格式符
  • 格式串与实际输入不匹配:你的输入字符串包含毫秒部分、Z时区标识,你定义的yyyy-MM-ddhh:mm:ss完全没有覆盖这部分内容
  • 入参存在多余符号:报错信息显示你的输入字符串前后多了双引号,需要先清理冗余符号

正确实现代码

基于SimpleDateFormat(兼容Java 8之前版本)

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public static Date parseDate(String publishedDate) {
    // 清理入参前后的多余双引号
    String cleanDateStr = publishedDate.replaceAll("^\"|\"$", "");
    SimpleDateFormat formatter = null;
    Date date = null;
    try {
        if (cleanDateStr.contains("T")) {
            // 单引号包裹T作为固定字符,HH对应24小时制,7个S匹配7位毫秒,X匹配Z时区标识
            formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSX");
            // 统一设置时区为UTC和Z标识对应
            formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        } else {
            formatter = new SimpleDateFormat("yyyy-MM-dd");
        }
        date = formatter.parse(cleanDateStr);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date;
}

基于Java 8+ DateTimeFormatter(推荐,线程安全)

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public static Date parseDate(String publishedDate) {
    // 清理入参前后的多余双引号
    String cleanDateStr = publishedDate.replaceAll("^\"|\"$", "");
    if (cleanDateStr.contains("T")) {
        // 内置的ISO_INSTANT天然支持带Z后缀的标准ISO 8601格式,无需自定义格式串
        Instant instant = Instant.parse(cleanDateStr);
        return Date.from(instant);
    } else {
        LocalDate localDate = LocalDate.parse(cleanDateStr, DateTimeFormatter.ISO_LOCAL_DATE);
        return Date.from(localDate.atStartOfDay(ZoneOffset.UTC).toInstant());
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:24:00