convert 日期格式_Spring对LocalDateTime入参接口返回值格式化

背景

使用过java8的朋友应该都知道LocalDateTime类型,它作为全新的日期和时间API ,对比Date类型有着很大的优势,极大的方便了我们对于时间和日期的操作。不过,如果在日常使用中,如果我们不对这个类型的字段进行处理的话,在打印或者直接返回到页面的时候往往看到的格式是这样的 2020-11-11T22:12:03.793 。显然这种格式对于用户来说阅读体验很差,那么,今天我们将通过这篇文章来介绍一下在使用LocalDateTime是如何在接受参数和返回信息时进行格式化。

测试

我们有如下类,供测试

UserVO.java

public class UserVO {     private String userName;    private String sex;    private LocalDateTime birthday;    //省略Getter and Setter方法 }

1.接收参数时进行格式化

① post请求使用formdata进行传参,这种情况下只需要在变量上添加@DateTimeFormat注解,案例如下:

public class UserVO {    private String userName;    private String sex;    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")    private LocalDateTime birthday;    //省略Getter and Setter方法}
@PostMapping("/testLocalDateTime")public UserVO testLocalDateTime(UserVO userVO) {    System.out.println(userVO);    return userVO;}
4d046f796135804e17822271354ed734.png

调用之后可以看到控制台成功打印相关信息:

74fff238f7db65e8d7157cd7f96cfad6.png

接口返回:

2052f91c502145f3b0c404ebf7c86142

② 使用post请求传参,并将参数放在请求体中,此时,需要在接口的实体类前添加@RequestBody注解,同时在LocalDateTime类型的变量上添加 @JsonFormat注解,案例如下:

private String userName;private String sex;@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")private LocalDateTime birthday;//省略Getter and Setter方法
@PostMapping("/testLocalDateTime2")public UserVO testLocalDateTime2(@RequestBody UserVO userVO) {    System.out.println(userVO.toString());    return userVO;}
2963335a5793a802d61b619ac54db4d6.png

调用之后一样可以看到控制台成功打印相关信息:

b9f2b86ab7306445bf960f75b16eeda9.png

并且接口返回如下信息:

8a60a18159ff49de29341281da7650ec.png

这里我们可以注意到:这种情况下不需要添加额外配置,也会对返回值进行格式化

补充

如果项目中返回LocalDateTime类型字段过多的话一个一个去添加@JsonFormat显然是不合理的,那么我们可以在项目中添加如下配置,即可对所有LocalDateTime类型进行序列化和反序列化。

LocalDateTimeConvertConfig.java

此配置使用于第一种情况,通过formDate进行传参

import lombok.extern.slf4j.Slf4j;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.convert.converter.Converter; import java.time.LocalDateTime;import java.time.format.DateTimeFormatter;  @Slf4j@Configurationpublic class LocalDateTimeConvertConfig {    @Bean    public Converter localDateTimeConvert() {        return new Converter() {            @Override            public LocalDateTime convert(String source) {                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");                LocalDateTime dateTime = null;                try {                    //2020-01-01 00:00:00                    switch (source.length()) {                        case 10:                            log.debug("传过来的是日期格式:{}", source);                            source = source + " 00:00:00";                            break;                        case 13:                            log.debug("传过来的是日期 小时格式:{}", source);                            source = source + ":00:00";                            break;                        case 16:                            log.debug("传过来的是日期 小时:分钟格式:{}", source);                            source = source + ":00";                            break;                    }                    dateTime = LocalDateTime.parse(source, df);                } catch (Exception e) {                    log.error(e.getMessage(), e);                }                return dateTime;            }        };    }}LocalDateTimeSerializerConfig.java

此配置使用于第二种情况,将请求参数放在requestbody中,可配合上一个文件使用

import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;import lombok.extern.slf4j.Slf4j;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; @Slf4j@Configurationpublic class LocalDateTimeSerializerConfig {     @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")    private String pattern;     // localDateTime 序列化器    @Bean    public LocalDateTimeSerializer localDateTimeSerializer() {        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));    }     // localDateTime 反序列化器    @Bean    public LocalDateTimeDeserializer localDateTimeDeserializer() {        return new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(pattern));    }     @Bean    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {//        return new Jackson2ObjectMapperBuilderCustomizer() {//            @Override//            public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {//                jacksonObjectMapperBuilder.featuresToDisable(SerializationFeature.FAIL_ON_EMPTY_BEANS);//                jacksonObjectMapperBuilder.serializerByType(LocalDateTime.class, localDateTimeSerializer());//                jacksonObjectMapperBuilder.deserializerByType(LocalDateTime.class, localDateTimeDeserializer());//            }//        };        //这种方式同上        return builder -> {            builder.serializerByType(LocalDateTime.class, localDateTimeSerializer());            builder.deserializerByType(LocalDateTime.class, localDateTimeDeserializer());            builder.simpleDateFormat(pattern);        };    }}

总结

今天这篇文章主要讲解了springboot中如何对LocalDateTime进行格式化,同时还提供了配置类来更加方便的全局格式化LocalDateTime格式。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值