四种Springboot常见全局时间格式化方式

 更新时间:2023年12月15日 09:52:16   作者:小小兔在普陀山走神啊  
这篇文章主要为大家详细介绍了Springboot实现全局时间格式化的四种常见方式,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

背景

Springboot 全局时间格式化,前后端日期类型参数格式化。

解决

方式大部分四种

1 @JsonFormat

字段加上 @JsonFormat 注解后,LocalDateTime 和 Date 时间格式化成功。需要在每个字段上添加该注解,不算全局时间格式化。不推荐

import com.fasterxml.jackson.annotation.JsonFormat;

@Data
public class TestDTO{

    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createTime;

    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    private Date updateTime;
}

2 配置文件配置参数

这种方式只对 Date 类型生效。不推荐

spring:
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8

3 @JsonComponent

自定义Configuration类。

Date、LocalDateTime类型日期均生效

推荐

/**
 * 全局日期格式化 如果某个字段不使用该格式
 * 依旧可以使用 @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd") 修改某个字段的格式化信息,且@JsonFormat优先级高于@JsonComponent配置的格式类型
 */
@JsonComponent
@Configuration
public class DateFormatConfig {

    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    /**
     * 类型全局时间格式化
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilder() {
        return builder -> {
            TimeZone tz = TimeZone.getTimeZone("GMT+8");
            DateFormat df = new SimpleDateFormat(pattern);
            df.setTimeZone(tz);
            builder.failOnEmptyBeans(false)
                    .failOnUnknownProperties(false)
                    .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                    .dateFormat(df);
        };
    }

    /**
     * 类型全局时间格式化
     */
    @Bean
    public LocalDateTimeSerializer localDateTimeDeserializer() {
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
    }

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

4 @Configuration

这种全局配置的实现方式与上边的效果是一样的。

注意:在使用此种配置后,字段手动配置@JsonFormat 注解将不再生效。

不推荐

@Configuration
public class DateFormatConfig2 {

    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    public static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Bean
    @Primary
    public ObjectMapper serializingObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
        objectMapper.registerModule(javaTimeModule);
        return objectMapper;
    }

    /**
     * 时间类型装换
     */
    @Component
    public class DateSerializer extends JsonSerializer<Date> {
        @Override
        public void serialize(Date date, JsonGenerator gen, SerializerProvider provider) throws IOException {
            String formattedDate = dateFormat.format(date);
            gen.writeString(formattedDate);
        }
    }

    /**
     * 时间类型装换
     */
    @Component
    public class DateDeserializer extends JsonDeserializer<Date> {

        @Override
        public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
            try {
                return dateFormat.parse(jsonParser.getValueAsString());
            } catch (ParseException e) {
                throw new RuntimeException("Could not parse date", e);
            }
        }
    }

    /**
     * 时间类型装换
     */
    public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
        @Override
        public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeString(value.format(DateTimeFormatter.ofPattern(pattern)));
        }
    }

    /**
     * 时间类型装换
     */
    public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
        @Override
        public LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext) throws IOException {
            return LocalDateTime.parse(p.getValueAsString(), DateTimeFormatter.ofPattern(pattern));
        }
    }
}

到此这篇关于四种Springboot常见全局时间格式化方式的文章就介绍到这了,更多相关Springboot全局时间格式化内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java中的八种基本数据类型详解

    Java中的八种基本数据类型详解

    本文详细讲解了Java中的八种基本数据类型,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-03-03
  • java 排序算法之快速排序

    java 排序算法之快速排序

    这篇文章主要介绍了java 排序算法之快速排序,文中通过图片和代码讲解相关知识非常详细,大家如果有需要的话可以参考一下这篇文章
    2021-09-09
  • 详解Springboot2.3集成Spring security 框架(原生集成)

    详解Springboot2.3集成Spring security 框架(原生集成)

    这篇文章主要介绍了详解Springboot2.3集成Spring security 框架(原生集成),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-08-08
  • SpringBoot中@Value获取值和@ConfigurationProperties获取值用法及比较

    SpringBoot中@Value获取值和@ConfigurationProperties获取值用法及比较

    在Spring Boot中,@Value注解是一个非常有用的特性,它允许我们将外部的配置注入到我们的Bean中,@ConfigurationProperties用于将配置文件中的属性绑定到 Java Bean 上,本文介绍了@Value获取值和@ConfigurationProperties获取值用法及比较,需要的朋友可以参考下
    2024-08-08
  • Java如何将字符串String转换为整型Int

    Java如何将字符串String转换为整型Int

    这篇文章主要介绍了Java如何将字符串String转换为整型Int,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的朋友可以参考一下
    2022-08-08
  • spring boot mybatis枚举映射示例代码

    spring boot mybatis枚举映射示例代码

    这篇文章主要给大家介绍了关于spring boot mybatis枚举映射的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Spring Boot具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-09-09
  • Java进程与线程介绍及如何实现

    Java进程与线程介绍及如何实现

    进程(Process)是计算机中执行的程序的实例,它是操作系统分配资源和调度的基本单位,本文给大家介绍Java进程与线程的相关介绍及如何实现,感兴趣的朋友跟随小编一起看看吧
    2025-10-10
  • Java卡片布局管理器解释及实例

    Java卡片布局管理器解释及实例

    这篇文章主要介绍了Java卡片布局管理器解释及实例,需要的朋友可以参考下。
    2017-09-09
  • SpringBoot服务设置禁止server.point端口的使用

    SpringBoot服务设置禁止server.point端口的使用

    本文主要介绍了SpringBoot服务设置禁止server.point端口的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-01-01
  • Object类toString()和equals()方法使用解析

    Object类toString()和equals()方法使用解析

    这篇文章主要介绍了Object类toString()和equals()方法使用解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-02-02

最新评论