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

Java字符串与Date格式互转出现Unparseable date报错如何解决

问题原因解析

你报错的核心是SimpleDateFormat初始化传入的格式模板,和待解析的输入字符串实际格式不匹配:
待解析的字符串20211109的格式为yyyyMMdd(4位年份+2位月份+2位日期,无分隔符),但你传入的模板是MM/dd/yyyy(月份/日期/年份,斜杠分隔),格式规则完全不匹配,所以抛出解析失败异常。

正确实现方案

方案1:使用SimpleDateFormat(适配Java7及更早版本)

需要分别定义输入字符串的解析模板和输出目标的格式化模板,代码示例:

String inputDateStr = "20211109";
// 定义输入字符串对应的解析格式
SimpleDateFormat inputParser = new SimpleDateFormat("yyyyMMdd");
// 字符串转Date对象
Date strtDt = inputParser.parse(inputDateStr);
// 定义你需要输出的目标格式
SimpleDateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
// Date转目标格式字符串
String strt = outputFormatter.format(strtDt);

注意:SimpleDateFormat是线程不安全的,多线程场景下不要定义为全局静态变量直接复用,避免出现格式错乱、异常报错问题。

方案2:使用java.time包类(推荐,Java8及以上版本)

Java8引入的新日期时间API线程安全,API设计更合理,避免老版本的诸多问题,代码示例:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DateConvertDemo {
    public static void main(String[] args) {
        // 输入字符串的解析模板
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        // 字符串转日期对象
        LocalDate localDate = LocalDate.parse("20211109", inputFormatter);
        // 目标输出格式模板
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
        // 日期对象转目标格式字符串
        String formattedDate = localDate.format(outputFormatter);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 13:15:08