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

Java中如何将日期字符串转换为另一种格式?

问题分析与解决

1. 核心错误点

  • 解析格式错误:你用了dd-mmm-yy,但SimpleDateFormat中月份缩写的正确模式是大写MMM,小写mmm属于无效格式,这是触发ParseException的关键原因。
  • 区域设置缺失:Apr是英文月份缩写,如果程序默认Locale不是英文(比如中文环境),解析器无法识别该缩写,同样会抛出异常。
  • 格式化格式错误:输出用的dd/mm/yy里,小写mm代表分钟,要输出月份必须用大写MM。

修正后的代码

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

// 假设CustomInternalServerException已定义
public class DateConverter {
    public static String convertDate(String oldDate) throws ParseException {
        // 指定英文Locale,确保识别英文月份缩写
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy", Locale.ENGLISH);
        Date dt = sdf.parse(oldDate);

        // 用MM表示月份(mm是分钟)
        SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yy");
        return sdf1.format(dt);
    }
}

更优方案:使用Java 8+日期API

SimpleDateFormat存在线程不安全问题,推荐用Java 8引入的java.time包,API更清晰且安全:

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

public class ModernDateConverter {
    public static String convertDate(String oldDate) {
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MMM-yy", Locale.ENGLISH);
        LocalDate date = LocalDate.parse(oldDate, inputFormatter);
        
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd/MM/yy");
        return date.format(outputFormatter);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 13:22:07