1. 程式人生 > 實用技巧 >LocalDateTime入參和介面返回值格式化

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;
    }

呼叫之後可以看到控制檯成功列印相關資訊:

介面返回:

使用post請求傳參,並將引數放在請求體中,此時,需要在介面的實體類前新增@RequestBody註解,同時在LocalDateTime型別的變數上新增@JsonFormat註解,案例如下:

    private String userName;
    private String sex;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime birthday;
    //省略Getter and Setter方法

呼叫之後一樣可以看到控制檯成功列印相關資訊:

並且介面返回如下資訊:

這裡我們可以注意到:這種情況下不需要新增額外配置,也會對返回值進行格式化

tips:如果專案中返回LocalDateTime型別欄位過多的話一個一個去新增@JsonFormat顯然是不合理的,那麼我們可以在專案中新增如下配置,即可對所有返回的LocalDateTime型別進行格式化

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 LocalDateTimeSerializerConfig {

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