Spring Boot 全局日期时间格式化需统一Jackson序列化与Spring MVC参数绑定:配置文件设置jackson.date-format和time-zone仅对Date生效;Java 8类型需通过JavaTimeModule注册LocalDateTime/LocalDate的序列化器与反序列化器;请求参数解析需配置spring.mvc.date-format或自定义Formatter。

Spring Boot 全局配置日期时间格式化,核心是统一控制 Jackson 序列化(响应返回)和 Spring MVC 参数绑定(请求接收)两个方向的日期处理逻辑。最常用、最推荐的方式是配置 + 编程结合,兼顾简洁性与兼容性。
配置文件方式:快速生效,适合 Date 类型
在 application.yml 中添加:
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
serialization:
write-dates-as-timestamps: false
或 application.properties:
立即学习“Java免费学习笔记(深入)”;
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
spring.jackson.serialization.write-dates-as-timestamps=false
⚠️ 注意:该方式默认只对 Date 类型生效;对 LocalDateTime、LocalDate 等 Java 8 时间类型无效,需额外配置模块。
Java 8 时间类型支持:通过 Jackson 配置类补全
创建一个 @Configuration 类,注册 JavaTimeModule 并指定格式器:
@Configuration
public class JacksonConfig {
@Bean
@Primary
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
JavaTimeModule module = new JavaTimeModule();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
module.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
module.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
mapper.registerModule(module);
return mapper;
}
}
这样,所有 LocalDateTime 和 LocalDate 字段在 JSON 响应中都会按指定格式输出,无需每个字段加 @JsonFormat。
请求参数自动解析:配置 spring.mvc.date-format
前端传参如 ?startTime=2025-10-01 14:30:00,后端用 LocalDateTime 接收时,需让 Spring 能正确转换。在配置文件中加:
spring.mvc.date-format=yyyy-MM-dd HH:mm:ss
该配置相当于为所有 @DateTimeFormat 注解提供默认 pattern,适用于 Controller 方法参数或实体类字段绑定场景。
更灵活的请求多格式支持(可选进阶)
如果前端可能传多种格式(如 2025-10-01、2025/10/01、01-10-2025),可自定义 Converter


















