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

Java使用SimpleDateFormat转换日期2019-04-24为24-Apr-2019出错如何解决

问题原因
  • 错误使用DD代表月份中的天数:SimpleDateFormat中,大写D对应的是年中天(一年中的第几天),小写d才是月中天(一个月中的第几天)。你传入的日期2019-04-24用源格式yyyy-MM-DD解析时,24会被识别为2019年的第24天,也就是1月24日,自然输出月份为Jan。
  • 错误使用YY代表公历年:大写Y是周年(和周数计算绑定的特殊纪年规则),日常日期处理要使用小写y代表公历年。你需要输出四位年份,所以要写yyyy而非两位的yy。
  • 补充:如果需要输出英文月份缩写Apr,需要给SimpleDateFormat指定英文Locale,否则默认中文Locale下会输出四月。
修正后的代码
// 工具方法增加Locale参数适配多语言月份输出,核心逻辑无需调整
public static String dateFormatConvert(String date, String srcDateFormat, String targetDataFormat, Locale locale) throws ParseException {
    DateFormat dateFormat = new SimpleDateFormat(srcDateFormat, locale);
    Date srcDate = dateFormat.parse(date);
    DateFormat destDateFormat = new SimpleDateFormat(targetDataFormat, locale);
    return destDateFormat.format(srcDate);
}

// 调用时替换正确的格式串,指定英文Locale
String date1 = CommonUtil.dateFormatConvert("2019-04-24", "yyyy-MM-dd", "dd-MMM-yyyy", Locale.ENGLISH);
System.out.println(date1); // 输出 24-Apr-2019
额外注意事项
  • SimpleDateFormat是非线程安全类,不要在多线程场景下定义为静态变量复用,否则会出现并发异常。
  • 如果使用JDK8及以上版本,更推荐使用java.time包下的DateTimeFormatter,该类是线程安全的,API设计更合理不易出错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 00:24:02