springboot全局时间格式化

2022年10月28日12:14:24

前言

这边一直用的返回参数加 @JsonFormat 注解的方式对日期进行格式化,但偶尔会出现忘记格式化(忘记添加注解的问题),遂在此添加全局配置,顺带做个笔记
springboot全局时间格式化

方法1:项目配置

这种方式只对 Date 类型生效

# 日期统一格式化spring:jackson:date-format: yyyy-MM-dd HH:mm:sstime-zone: GMT+8

下面这个也是亲测OK

# 日期统一按时间戳返回
spring.jackson.serialization.write-dates-as-timestamps=true

方法二:@JsonFormat

部分格式化:@JsonFormat 注解需要用在实体类的时间字段上,对应的字段才能进行格式化。

@Getter@SetterpublicclassTestTime{@JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss")privateDate date;privateLocalDateTime localDateTime;@JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyyMMdd")privateLocalDate localDate;@JsonFormat(locale="zh", timezone="GMT+8", pattern="HHmmss")privateLocalTime localTime;}

方法三:@JsonComponent

使用 @JsonComponent 注解自定义一个全局格式化类,分别对 Date 和 LocalDate 类型做格式化处理。

@JsonComponentpublicclassJsonComponentConfig{@Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")privateString pattern;/**
     * date 类型全局时间格式化
     */@BeanpublicJackson2ObjectMapperBuilderCustomizerjackson2ObjectMapperBuilder(){return builder->{TimeZone tz=TimeZone.getTimeZone("UTC");DateFormat df=newSimpleDateFormat(pattern);
            df.setTimeZone(tz);
            builder.failOnEmptyBeans(false).failOnUnknownProperties(false).featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS).dateFormat(df);};}/**
     * LocalDate 类型全局时间格式化
     */publicLocalDateTimeSerializerlocalDateTimeDeserializer(){returnnewLocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));}@BeanpublicJackson2ObjectMapperBuilderCustomizerjackson2ObjectMapperBuilderCustomizer(){return builder-> builder.serializerByType(LocalDateTime.class,localDateTimeDeserializer());}}
  • 作者:灼烧的疯狂
  • 原文链接:https://blog.csdn.net/qq_33803102/article/details/120038871
    更新时间:2022年10月28日12:14:24 ,共 1523 字。