怎么处理Springboot版本升级后引起的时间序列化格式问题

158 阅读2分钟

一、背景

在一次代码重构时,由于Springboot及相关版本的升级(升级到SpringBoot3.2.5),突然发现前端过来吐槽说,我们为什么要把时间格式改得那么奇怪,前端处理起来也是很费劲,后来找了一下相关官方文档,主要有两个原因,在此附上相关原文:

  1. Jackson, the default JSON serialization library used by Spring Boot, adheres to the ISO 8601 standard for datetime formatting. This standard includes the full timestamp with milliseconds and timezone offset (e.g., 2023-02-23T00:00:00.000+00:00).
  1. Spring Boot 3.x enhances support for Java 8+ java.time classes (like LocalDateTime, ZonedDateTime, etc.) through the JavaTimeModule in Jackson. This module ensures that datetime fields are serialized in a fully qualified ISO 8601 format by default.

简单点总结:

  1. 时间格式序列化错误,默认采用了更加详细的ISO 8601日期格式,所以出现了"2023-02-23T00:00:00.000+00:00",这个恶魔。

二、如何解决?

既然知道了是序列化的问题,那么处理起来就有很多种方式了,特别是在我们采用SpringBoot框架构建项目的时候,我主要推荐两种方式,大家可以按照自己的需要选择,并且可以尝试更多其他的解决办法:

  • 使用@JsonFormat注解

合格的java程序员,直接看下面代码即可,我想不需要太多的解释。

import com.fasterxml.jackson.annotation.JsonFormat; 
import java.time.LocalDateTime; 
public class AgencyCompanyDTO { 
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Shanghai") 
    private LocalDateTime startTime; 
    // Other fields and methods... 
    
}
  • 配置application.yml(注意:如果是Nacos,直接修改Nacos配置文件就好)
spring: 
    jackson: 
        date-format: yyyy-MM-dd HH:mm:ss 
        time-zone: Asia/Shanghai

或者properties格式:

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss 
spring.jackson.time-zone=Asia/Shanghai

三、总结

核心问题就是Jackson序列化,只要抓住了重点怎么合理就怎么调整即可解决问题,这里修改的主要意图是想和相关日期格式的标准靠拢,格式进行了规范处理。