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

使用DateTimeFormatter解析日期字符串为LocalDateTime遇DateTimeParseException求助

问题排查与解决方案

你的代码抛出DateTimeParseException主要有两个原因:

1. 时区格式符号不匹配

你使用的XXXX格式符对应带冒号的时区偏移(如+01:00),但目标字符串中的时区是不带冒号的+0100,正确的格式符应该是XX。

2. 缺少英文Locale支持

DateTimeFormatter默认使用JVM的系统Locale,如果你的默认Locale不是英文,无法识别Mon(星期缩写)、Nov(月份缩写)这类英文标识,必须显式指定英文Locale。

修正后的代码

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class DateParser {
    public static void main(String[] args) {
        String fecha = "Mon, 07 Nov 2022 21:00:00 +0100";
        
        // 指定英文Locale,同时修正时区格式符为XX
        DateTimeFormatter formato = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss XX", Locale.ENGLISH);    
        LocalDateTime fechaHora = LocalDateTime.parse(fecha, formato);
        
        System.out.println(fechaHora); // 输出:2022-11-07T21:00
    }
}

额外建议:保留时区信息的正确姿势

LocalDateTime本身不包含时区偏移信息,解析时会直接忽略字符串中的时区部分。如果需要处理时区相关逻辑,推荐使用OffsetDateTime来存储完整的带偏移量的日期时间,之后再按需转换为LocalDateTime:

import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class DateParser {
    public static void main(String[] args) {
        String fecha = "Mon, 07 Nov 2022 21:00:00 +0100";
        
        DateTimeFormatter formato = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss XX", Locale.ENGLISH);    
        OffsetDateTime offsetDateTime = OffsetDateTime.parse(fecha, formato);
        
        // 转换为LocalDateTime(丢弃时区偏移)
        LocalDateTime fechaHora = offsetDateTime.toLocalDateTime();
        
        System.out.println("带时区的日期时间:" + offsetDateTime); // 输出:2022-11-07T21:00+01:00
        System.out.println("本地日期时间:" + fechaHora); // 输出:2022-11-07T21:00
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 00:01:12