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

Spring使用dd-MM-yyyy格式时LocalDate字段验证失败问题

解决Spring中LocalDate字符串转换验证错误

问题场景

实体类中定义的LocalDate字段:

@DateTimeFormat(pattern="dd-MM-YYYY")
private LocalDate myDate;

现有一个Date对象,打印显示为Thu Jul 07 00:00:00 IST 2022,转换为LocalDate的代码如下:

LocalDate myLocalDate = LocalDate.ofInstant(myDateObj.toInstant(), ZoneId.of("Asia/Kolkata"));

该日期在数据库中存储为2022-07-07,页面上能正常显示为预期的07-07-2022,但在网页上以相同格式编辑保存时,出现如下验证错误:

Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDate' for property 'myDate'; Failed to convert from type [java.lang.String] to type [@org.springframework.format.annotation.DateTimeFormat java.time.LocalDate] for value [07-07-2022]

解决方案

核心原因

@DateTimeFormat注解中误用了YYYY(代表基于周的年份,即周年),而非yyyy(公历年)。虽然显示时07-07-2022外观正常,但Spring解析字符串转LocalDate时,YYYY的解析逻辑会导致日期匹配失败,触发转换错误。

修复操作

修改实体类中的日期格式注解,将YYYY替换为yyyy:

@DateTimeFormat(pattern="dd-MM-yyyy")
private LocalDate myDate;

补充建议

如果项目涉及JPA持久化或前后端JSON交互,可配合添加@JsonFormat注解,确保序列化/反序列化的一致性:

@DateTimeFormat(pattern="dd-MM-yyyy")
@JsonFormat(pattern="dd-MM-yyyy", timezone="Asia/Kolkata")
private LocalDate myDate;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 05:32:07