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

Java中解析日期遇Unparseable date异常求助

问题解决:日期解析失败与格式转换实现

错误原因

  • 格式符号使用错误:
    • 星期缩写需用EEE,而非代码中的Www
    • 月份缩写需用MMM,而非代码中的Mmm
    • 年份应使用yyyy(表示公历年),而非YYYY(表示周年,用于周历计算,通常与实际年份不符)
  • 未指定Locale:输入日期为英文格式,若系统默认Locale非英文,会导致解析失败,需显式指定Locale.ENGLISH

修正后的传统API实现(SimpleDateFormat)

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

public void parseDate(String stringDate) {
    // 修正格式规则并指定英文Locale
    SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy", Locale.ENGLISH);
    // 目标输出格式
    SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
    
    try {
        Date date = inputFormat.parse(stringDate);
        // 转换为目标格式并输出
        String formattedDate = outputFormat.format(date);
        System.out.println(formattedDate);
    } catch (ParseException parseException) {
        System.out.println(parseException.getMessage());
    }
}

推荐的Java 8+新日期API实现(java.time包)

SimpleDateFormat存在线程不安全、API设计冗余等问题,推荐使用Java 8引入的java.time系列API:

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

public void parseDate(String stringDate) {
    DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss yyyy", Locale.ENGLISH);
    DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");
    
    try {
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(stringDate, inputFormatter);
        String formattedDate = zonedDateTime.format(outputFormatter);
        System.out.println(formattedDate);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 05:22:15