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

无法将含AM/PM的字符串转换为Date对象的技术问题

解决带有AM/PM的日期字符串转Date的ParseException问题

我来帮你搞定这个解析异常的问题!你遇到的java.text.ParseException,核心原因是没有指定合适的Locale。

问题根源

你的日期格式里用到了MMM(英文月份缩写,比如"May")和a(AM/PM标识),但SimpleDateFormat默认会使用当前系统的Locale。如果你的系统Locale不是英文(比如中文、日文等),它就无法识别这些英文格式的日期元素,自然就抛出解析异常了。

解决方案1:给SimpleDateFormat指定英文Locale

只需要在创建SimpleDateFormat的时候,显式传入Locale.ENGLISH,就能让它按照英文规则解析日期字符串了。修正后的代码如下:

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

public static Date parseDate() {
    String format = "dd-MMM-yyyy HH:mm:ss a";
    String sdate = "07-May-2018 12:00:00 AM";
    Date util_sdate = null;
    try {
        // 关键:添加Locale.ENGLISH指定英文解析规则
        SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.ENGLISH);
        sdf.setLenient(false);
        util_sdate = sdf.parse(sdate);
    } catch (ParseException pe) {
        pe.printStackTrace();
    }
    return util_sdate;
}

解决方案2:推荐使用Java 8+的新日期API(更安全可靠)

SimpleDateFormat是线程不安全的,而且属于Java早期的过时API。如果你的项目使用Java 8及以上版本,更推荐使用java.time包下的新日期类,它们线程安全、API设计更清晰。示例代码如下:

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.Locale;

public static Date parseDate() {
    String format = "dd-MMM-yyyy HH:mm:ss a";
    String sdate = "07-May-2018 12:00:00 AM";
    try {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format, Locale.ENGLISH);
        LocalDateTime localDateTime = LocalDateTime.parse(sdate, formatter);
        // 将LocalDateTime转换为Date类型
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    } catch (DateTimeParseException e) {
        e.printStackTrace();
        return null;
    }
}

总结

  • 解析包含英文日期元素的字符串时,一定要显式指定Locale.ENGLISH,避免系统Locale带来的解析失败。
  • 优先使用Java 8+的java.time系列API,替代老旧的SimpleDateFormat和Date类,减少潜在问题。

内容的提问来源于stack exchange,提问作者SYAM KRISHNA MG

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:50:20