全局配置LocalDateTime,实现日期格式化(Date日期格式也通用)

时间:2025-05-12 09:28:41

1、首先在配置文件中添加以下配置信息,确定日期格式,供下面配置类中进行读取

Spring:
  jackson:
    date-format: yyyy-MM-dd HH:mm

2、新建配置类,在程序运行初始化时进行加载,将日期格式进行转化

import .;
import ;
import .Jackson2ObjectMapperBuilderCustomizer;
import ;
import ;

import ;
import ;

/**
 * @author: SUN
 * @version: 1.0
 * @date: 2019/12/31 15:39
 * @description: 全局配置LocalDateTime,实现格式化
 */

@Configuration
public class LocalDateTimeSerializerConfig {

    // 此处通过Value注解读取配置文件中的 date-format
    @Value("${-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    @Bean
    public LocalDateTimeSerializer localDateTimeDeserializer() {
        return new LocalDateTimeSerializer((pattern));
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> (, localDateTimeDeserializer());
    }

}

3、如果某些实体类中的日期无法实现格式转换,在实体类的字段上配合使用  @JsonFormat(pattern = "yyyy-MM-dd HH:mm")  

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm")
    private LocalDateTime createAt;

4、转换之前日期格式为 2019-12-30T17:15:23 通过配置类进行转换之后的日期格式为 2019-12-30 17:15  且去除了秒的显示。