SpringBoot统一LocalDateTime日期格式化输出

demo

SpringBoot统一LocalDateTime日期格式化输出,输出格式如下图
在这里插入图片描述

@JsonComponent
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("UTC");
            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());
    }
}

实际开发中如果我有个字段不想用全局格式化设置的时间样式,想自定义,就需要和 @JsonFormat 注解配合使用了

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot 2.5版本中,可以通过配置全局的LocalDateTime格式化来实现统一日期时间展示方式。首先,我们需要在项目中定义一个全局的DateTimeFormatter对象,用于格式LocalDateTime类型的日期时间数据。可以在配置类中使用@Bean注解将其定义为一个Bean,如下所示: ```java @Configuration public class DateTimeConfig { @Bean public DateTimeFormatter dateTimeFormatter() { return DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); } } ``` 然后,在需要格式LocalDateTime类型的字段上使用@JsonFormat注解,指定使用全局的DateTimeFormatter进行格式化,如下所示: ```java public class ExampleEntity { @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime dateTime; // getter and setter methods } ``` 这样,在返回给前端或从前端接收的JSON数据中,LocalDateTime类型的字段会按照指定格式进行格式化和反格式化。例如,LocalDateTime字段的数据为2022-05-31T12:34:56,通过全局的格式化设置后,展示给前端的数据会变为"2022-05-31 12:34:56"。 需要注意的是,上述配置和注解需要结合使用,才能实现全局的LocalDateTime格式化。另外,根据具体需求,可以灵活调整DateTimeFormatter的格式,以满足项目的需求。 以上就是使用Spring Boot 2.5实现全局LocalDateTime格式化的方法。通过配置全局的DateTimeFormatter,并在需要格式化的字段上使用@JsonFormat注解,可以实现统一日期时间展示方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值