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

Java如何将日期格式化为yyyy-MM-dd?日期字符串转Date遇解析错误

Java日期解析与格式化问题解决方法

问题根源

你遇到的解析错误,核心原因是解析时用的日期格式与目标字符串格式不匹配:

  • 要解析的02.02.2023是德国地区的dd.MM.yyyy格式,但你用了yyyy-MM-dd的格式化器去解析,自然无法匹配。
  • 旧API的SimpleDateFormat报错同理,是因为你没有指定正确的解析格式和Locale。

解决方案

方案1:使用旧API(Date/SimpleDateFormat)

如果必须使用Date类型,先匹配字符串的格式解析,再转成目标格式输出:

// 第一步:用德国日期格式解析字符串为Date
SimpleDateFormat germanParser = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN);
Date date = germanParser.parse("02.02.2023");

// 第二步:将Date格式化为yyyy-MM-dd的字符串
SimpleDateFormat targetFormatter = new SimpleDateFormat("yyyy-MM-dd");
String targetDateStr = targetFormatter.format(date);

System.out.println(targetDateStr); // 输出:2023-02-02

注意:SimpleDateFormat不是线程安全的,多线程环境下要避免共享实例。

方案2:使用新API(java.time,推荐)

Java 8及以上推荐用java.time包的API,线程安全且设计更合理:

// 第一步:用德国格式解析字符串为LocalDate
DateTimeFormatter germanParser = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.GERMAN);
LocalDate localDate = LocalDate.parse("02.02.2023", germanParser);

// 第二步:格式化为yyyy-MM-dd的字符串
String targetDateStr = localDate.format(DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println(targetDateStr); // 输出:2023-02-02

// 如果需要转成旧的Date类型(兼容老代码)
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

关键说明

  • Date对象本身不存储格式,它只是表示一个时间戳,所谓的"格式"是在格式化输出时才体现的。如果你需要的是符合yyyy-MM-dd格式的字符串,直接用格式化器处理即可;如果必须拿到Date类型,解析后得到的对象就是正确的,只是toString()显示的格式不同而已。
  • 解析时必须保证格式化器的格式与输入字符串完全匹配,包括分隔符、日期顺序、Locale(比如德国的月份是数字,而有些地区是英文缩写)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 09:40:25