You need to enable JavaScript to run this app. OpenJDK11使用DateTimeFormatter解析带z时区日期抛出DateTimeParseException问题
优惠活动
大模型
产品
解决方案
定价
更多

OpenJDK11使用DateTimeFormatter解析带z时区日期抛出DateTimeParseException问题

问题原因
  • OpenJDK版本已知bug:你使用的OpenJDK 11.0.3存在编号为JDK-8221378的官方缺陷,在解析模式符z对应的时区短名称时,内部前缀树处理逻辑存在空指针问题,直接触发你遇到的NPE异常,该缺陷在OpenJDK 11.0.4及后续版本已完成修复。
  • 时间类型不匹配:即使修复了JDK版本问题,你当前使用LocalDate接收解析结果的写法也存在问题:LocalDate是不包含时区信息的时间类型,无法承载解析带时区字符串得到的时区属性,会额外抛出不兼容类型的解析异常。
解决方案(保留模式符z)

方案1:升级JDK版本(推荐)

将OpenJDK升级到11.0.4或更高版本,同时将接收解析结果的类型替换为带时区的ZonedDateTime,如果需要LocalDate可以自行转换,示例代码如下:

import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class DateTest {
    public static void main(String[] args) {
        String pattern = "EEE MMM dd HH:mm:ss z yyyy";
        String dateStr = "Thu Jan 01 01:00:00 CET 1970";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ENGLISH);
        // 用ZonedDateTime承接带时区的解析结果
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateStr, formatter);
        // 按需转换为LocalDate
        LocalDate date = zonedDateTime.toLocalDate();
        System.out.println("date ==> " + date);
    }
}

运行输出:
date ==> 1970-01-01

方案2:无法升级JDK的兼容方案

如果暂时无法升级JDK版本,可以通过DateTimeFormatterBuilder手动指定时区短名映射,绕过JDK的前缀树处理缺陷:

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.TextStyle;
import java.util.Locale;
import java.util.Set;

public class DateTest {
    public static void main(String[] args) {
        String pattern = "EEE MMM dd HH:mm:ss z yyyy";
        String dateStr = "Thu Jan 01 01:00:00 CET 1970";
        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .appendPattern(pattern)
                // 手动指定可识别的时区集合,避免触发前缀树空指针bug
                .appendZoneText(TextStyle.SHORT, Set.of(ZoneId.of("CET")))
                .toFormatter(Locale.ENGLISH);
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateStr, formatter);
        LocalDate date = zonedDateTime.toLocalDate();
        System.out.println("date ==> " + date);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 03:54:04