Spring MVC中@DateTimeFormat及Jackson日期格式化配置不生效该如何解决
问题原因
你之前的两个配置都不生效的核心原因是适配场景不对:
@DateTimeFormat注解仅用于处理请求参数绑定,也就是前端传入的字符串转后端日期对象的场景,不控制后端日期对象渲染到视图的输出格式spring.jackson.date-format仅控制Jackson序列化JSON时的日期格式,Thymeleaf是服务端渲染,不走Jackson序列化流程,因此该配置不生效
最优解决方案(仅修改application.properties全局生效)
Spring Boot 2.3及以上版本支持直接通过配置文件配置MVC全局日期格式,适配所有Timestamp、Date、LocalDateTime类型的参数绑定和视图渲染,完全不需要修改实体类或模板代码:
# 全局日期时间输出格式,适配Thymeleaf渲染 spring.mvc.format.date-time=yyyy-MM-dd hh:mm:ss aa # 配置 locale 为英文,确保AM/PM显示为英文而非中文的上午/下午 spring.web.locale=en_US spring.web.locale-resolver=fixed
配置完成后你原本的Thymeleaf代码不需要做任何修改,直接输出${problem.createdTime}就会自动按照你要的格式渲染。
低版本Spring Boot兼容方案
如果你的Spring Boot版本低于2.3,可以通过注册全局格式化器实现同样的全局效果,新增一个配置类即可:
import org.springframework.context.annotation.Configuration; import org.springframework.format.Formatter; import org.springframework.format.FormatterRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Locale; @Configuration public class WebDateConfig implements WebMvcConfigurer { @Override public void addFormatters(FormatterRegistry registry) { registry.addFormatterForFieldType(Timestamp.class, new Formatter<Timestamp>() { private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss aa", Locale.ENGLISH); @Override public Timestamp parse(String text, Locale locale) throws ParseException { return new Timestamp(dateFormat.parse(text).getTime()); } @Override public String print(Timestamp object, Locale locale) { return dateFormat.format(object); } }); } }
单个字段临时修改方案
如果有个别字段需要使用不同的格式,可以直接在Thymeleaf模板中使用内置的日期工具类处理,不需要改后端代码:
<td th:text="${#dates.format(problem.createdTime, 'yyyy-MM-dd hh:mm:ss aa')}" />
内容的提问来源于stack exchange,提问作者let me down slowly
相关产品推荐
相关产品推荐

