Springboot绑定Date类型时出现日期转换异常问题
一、问题核心描述
在调用接口 /device/list
时,前端传递日期字段 addTime
的格式 2025-07-17 13:30:18
,导致 Spring 类型转换失败,无法将字符串自动转为 Date
类型。
问题场景
- 请求类型:
GET
请求(使用@ModelAttribute
绑定参数) - 字段类型:
- 目标类型:
Date
- 传入值:字符串
"2025-07-17 13:30:18"
- 目标类型:
- 错误原因:
Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'bindTime'
二、总结:日期格式化场景的解决方案
1. GET请求 + @ModelAttribute
方式
解决方案: 使用 Spring的@DateTimeFormat
import org.springframework.format.annotation.DateTimeFormat;public class DeviceDto {@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")private Date addTime;
}
- 前端传参格式:
?addTime=2025-07-17+14:30:45
(需要正确URL编码) - 兼容传统
Date
类型
@ModelAttribute
参数绑定 不依赖 Jackson(@JsonFormat
无效)
2. POST请求 + @RequestBody
方式 (JSON格式)
解决方案: 使用 Jackson的@JsonFormat
import com.fasterxml.jackson.annotation.JsonFormat;public class DeviceDto {@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")private Date addTime;
}
- 前端传参格式:
{"addTime": "2025-07-17 14:30:45"}
3. 对于 @DateTimeFormat
是否支持 POST JSON 的问题
** @DateTimeFormat
不能 用于 @RequestBody
JSON 反序列化
使用建议总结
场景 | 推荐方案 | 前端传参示例 |
---|---|---|
GET + URL参数 | @DateTimeFormat | /path?addTime=2025-07-17 14:30 |
POST + 表单提交 | @DateTimeFormat | addTime=2025-07-17+14%3A30%3A45 |
POST + JSON请求体 | @JsonFormat | {"addTime":"2025-07-17 14:30"} |
需要同时支持所有格式 | 双注解+Java8 API | 任意格式 |
“表单数据用
@DateTimeFormat
,JSON数据用@JsonFormat
,Java8时间类型是终极解决方案”