SpringBoot 中LocalDateTime日期格式化

15 篇文章 0 订阅

 LocalDateTime 在GMT+8 默认格式为 yyyy-MM-ddTHH:mm:ss,如 2021-01-01T10:15:12
比如需要格式化为yyyy-MM-dd HH:mm:ss

1. 方式一

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

2. 方式二:全局配置

import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

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

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

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

 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在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注解,可以实现统一的日期时间展示方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值