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

Spring @DateTimeFormat接收POST参数时抛出异常问题排查

Spring MVC日期参数解析失败问题解决

错误原因

你的@DateTimeFormat配置的日期格式是英文规则(MMM对应英文月份缩写),但Spring MVC默认的Locale可能不是英文,导致无法识别Apr这类英文月份缩写,最终触发解析异常。另外,java.util.Date是老旧API,本身存在线程不安全等问题,也会增加解析风险。

解决办法

方案1:继续使用java.util.Date,指定英文Locale

在@DateTimeFormat注解里明确指定Locale为英文,让解析器按英文规则处理月份缩写:

import java.util.Date;
import java.util.Locale;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.RequestParam;

public void updateRecord(@RequestParam("dateAdded") 
                         @DateTimeFormat(pattern="MMM dd, yyyy, hh:mm:ss aa", locale = Locale.ENGLISH) 
                         Date dateAdded){
    // 业务逻辑
}

方案2:改用Java 8+日期API(推荐)

使用LocalDateTime替代Date,它是线程安全的类型,配合注解同样指定英文Locale:

import java.time.LocalDateTime;
import java.util.Locale;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.RequestParam;

public void updateRecord(@RequestParam("dateAdded") 
                         @DateTimeFormat(pattern="MMM dd, yyyy, hh:mm:ss aa", locale = Locale.ENGLISH) 
                         LocalDateTime dateAdded){
    // 业务逻辑
}

额外检查项

  • 确认POST参数的key是dateAdded,没有拼写错误;
  • 确认传递的参数值和测试字符串完全一致,无多余空格或格式差异。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 20:55:16