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

Java使用RFC_1123_DATE_TIME解析含时区标识的日期报错解决

问题描述

我通过以下代码从字符串中提取Date对象:

Date.from(ZonedDateTime.parse(exchange.getIn().getHeader("Date").toString(), DateTimeFormatter.RFC_1123_DATE_TIME).toInstant());

但当字符串为Tue, 26 Nov 2019 09:00:01 +0100 (CET)时出现解析错误。请问如何解析此类字符串并获取Date对象?是否需要使用其他DateTimeFormatter?

解决方案

问题核心是DateTimeFormatter.RFC_1123_DATE_TIME不支持解析末尾带时区名称(如(CET))的格式,需要自定义兼容该格式的DateTimeFormatter。

1. 构建自定义格式化器

使用DateTimeFormatterBuilder创建同时支持带/不带时区名称后缀的格式化器:

DateTimeFormatter customFormatter = new DateTimeFormatterBuilder()
        // 基础RFC_1123格式
        .appendPattern("EEE, dd MMM yyyy HH:mm:ss Z")
        // 标记时区名称部分为可选
        .optionalStart()
        .appendLiteral(" (")
        .appendZoneRegionId()
        .appendLiteral(")")
        .optionalEnd()
        // 指定英文Locale,避免本地化解析异常
        .toFormatter(Locale.ENGLISH);

2. 解析字符串并转换为Date

用自定义格式化器解析目标字符串,再转为Date对象:

String targetDateStr = "Tue, 26 Nov 2019 09:00:01 +0100 (CET)";
ZonedDateTime zonedDateTime = ZonedDateTime.parse(targetDateStr, customFormatter);
Date resultDate = Date.from(zonedDateTime.toInstant());

关键说明

  • Locale指定:必须传入Locale.ENGLISH,否则如果系统默认Locale非英文,解析Nov、Tue这类英文缩写会失败。
  • 兼容性:通过optionalStart()和optionalEnd()处理时区名称部分,这个格式化器同时兼容标准RFC_1123格式和带时区名称的扩展格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 09:55:00