SpringBoot幾種常用的接口日期格式化方法
全局時間格式化
通過在配置文件中設(shè)置可以實現(xiàn)全局時間格式化。在 Spring Boot 的配置文件 application.properties(或 application.yml)中添加以下兩行配置:
# 格式化全局時間字段 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss # 指定時間區(qū)域類型 spring.jackson.time-zone=GMT+8
實現(xiàn)原理分析:Controller 在返回數(shù)據(jù)時,會自動調(diào)用 Spring Boot 框架中內(nèi)置的 JSON 框架 Jackson,對返回的數(shù)據(jù)進(jìn)行統(tǒng)一的 JSON 格式化處理。在處理過程中,它會判斷配置文件中是否設(shè)置了 “spring.jackson.date-format=yyyy-MM-dd HH:mm:ss”,如果設(shè)置了,那么 Jackson 框架在對時間類型的字段輸出時就會執(zhí)行時間格式化的處理,從而實現(xiàn)全局時間字段的格式化功能。
部分時間格式化
在某些場景下,不需要對全局的時間都進(jìn)行統(tǒng)一處理,可以使用注解的方式實現(xiàn)部分時間字段的格式化。在實體類 UserInfo 中添加 @JsonFormat 注解,實現(xiàn)代碼如下:
import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.util.Date; @Data public class UserInfo { private int id; private String username; // 對 createtime 字段進(jìn)行格式化處理 @JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss", timezone = "GMT+8") private Date createtime; private Date updatetime; }
自定義參數(shù)轉(zhuǎn)換器
在 Spring Boot 中,可以使用自定義參數(shù)轉(zhuǎn)換器實現(xiàn)日期格式化。實現(xiàn) org.springframework.core.convert.converter.Converter接口,自定義參數(shù)轉(zhuǎn)換器,如下:
@Configuration public class DateConverterConfig { @Bean public Converter<String, LocalDate> localDateConverter() { return new Converter<String, LocalDate>() { @Override public LocalDate convert(String source) { return LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd")); } }; } @Bean public Converter<String, LocalDateTime> localDateTimeConverter() { return new Converter<String, LocalDateTime>() { @Override public LocalDateTime convert(String source) { return LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); } }; } }
在使用自定義參數(shù)轉(zhuǎn)換器時可能會遇到一些問題。例如,將匿名內(nèi)部類的寫法精簡成 lambda 表達(dá)式的方式時,啟動項目可能會出現(xiàn)異常。原因是 lambda 表達(dá)式的接口是 Converter,不能得到具體的類型。解決辦法有兩種:一是不使用 lambda 表達(dá)式,老老實實使用匿名內(nèi)部類;二是等 requestMappingHandlerAdapter bean 注冊完成之后再添加自己的 converter,這樣就不會注冊到 FormattingConversionService中。
此外,還可以對前端傳遞的 string 進(jìn)行正則匹配,如 yyyy-MM-dd HH:mm:ss、yyyy-MM-dd、HH:mm:ss等,以適應(yīng)多種場景。
使用 Spring 注解
Spring 自帶注解 @DateTimeFormat可以進(jìn)行日期格式化。它通常用于將字符串格式的日期轉(zhuǎn)換為日期類型。在需要進(jìn)行日期格式轉(zhuǎn)換的 Date屬性上添加注解 @DateTimeFormat(pattern = "需要轉(zhuǎn)換的格式")。例如:
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date birthday;
使用 @DateTimeFormat注解時需要注意,pattern指定的格式是和傳入的參數(shù)的格式相對應(yīng)。如果格式不對應(yīng),可能會拋出異常。
使用 ControllerAdvice 配合 initBinder
在 controller 做環(huán)切時,可以使用 initBinder進(jìn)行時間格式化。新建 InitBinderDateController類,進(jìn)行全局時間入?yún)⒏袷交?/p>
@ControllerAdvice public class InitBinderDateController { /** * 將前臺傳遞過來的日期格式的字符串,自動轉(zhuǎn)化為時間類型 * [攔截不到@RequestBody注解修飾的參數(shù)] */ @InitBinder("date") public void initBinder(WebDataBinder binder) { // Date 類型轉(zhuǎn)換 // DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // binder.registerCustomEditor(Date.class,new CustomDateEditor(dateFormat, true)); // System.out.println("test"); // LocalDateTime 類型轉(zhuǎn)換 binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() { @Override public void setAsText(String text) { if (!StringUtils.isEmpty(text)) { setValue(LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); } } }); } }
后端全局設(shè)置
可以通過配置后端實現(xiàn)全局請求日期格式轉(zhuǎn)換。例如,在配置文件中配置:
spring: jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8
或者使用配置類方式,適合前后端都是 json 格式交互。只需要用 @Configuration定義一個配置類,注入兩個 Bean即可完成全局日期響應(yīng)格式化處理。
@Configuration public class LocalDateTimeSerializerConfig { private static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; @Bean public LocalDateTimeSerializer localDateTimeSerializer() { return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS)); } @Bean public LocalDateTimeDeserializer localDateTimeDeserializer() { return new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS)); } @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { return builder -> { builder.serializerByType(LocalDateTime.class, localDateTimeSerializer()); builder.deserializerByType(LocalDateTime.class, localDateTimeDeserializer()); }; } }
接口輸出日期格式為時間戳
在 Spring Boot 中,實現(xiàn)接口輸出日期格式為時間戳的步驟如下:
- 配置日期格式化器:在 Spring Boot 的配置文件中,我們可以配置一個日期格式化器,將日期格式化為時間戳。可以在 application.properties(或 application.yml)中添加以下配置:spring.mvc.format.date=unix。
- 定義實體類:我們首先需要定義一個實體類,用于表示需要輸出的日期字段:
public class MyEntity { private Date date; // getter and setter }
- 編寫控制器:接下來,我們需要編寫一個控制器類,用于處理接口請求并返回日期字段的時間戳形式。我們可以使用 @JsonFormat注解來指定日期字段的格式化方式。下面是一個簡單的示例:
@RestController public class MyController { @GetMapping("/entity") public MyEntity getEntity() { MyEntity entity = new MyEntity(); entity.setDate(new Date()); return entity; } }
- 測試接口:啟動 Spring Boot 應(yīng)用后,我們可以通過訪問 /entity接口來獲取日期字段的時間戳形式??梢允褂?Postman 或瀏覽器等工具進(jìn)行測試。
GET /entity HTTP/1.1
Host: localhost:8080
響應(yīng)結(jié)果將會是一個 JSON 格式的對象,其中日期字段將以時間戳的形式表示。例如:
{ "date": 1678912345678 }
到此這篇關(guān)于SpringBoot幾種常用的接口日期格式化方法的文章就介紹到這了,更多相關(guān)SpringBoot接口日期格式化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot 錯誤處理機制與自定義錯誤處理實現(xiàn)詳解
這篇文章主要介紹了SpringBoot 錯誤處理機制與自定義錯誤處理實現(xiàn)詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11SpringBoot Mybatis批量插入Oracle數(shù)據(jù)庫數(shù)據(jù)
這篇文章主要介紹了SpringBoot Mybatis批量插入Oracle數(shù)據(jù)庫數(shù)據(jù),文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-08-08Java中的ConcurrentLinkedQueue松散隊列解析
這篇文章主要介紹了Java中的ConcurrentLinkedQueue松散隊列解析,鏈表是松散的,鏈表節(jié)點并不都是有效的,允許存在無效節(jié)點val=null,但是只有最后一個節(jié)點才能next=null,需要的朋友可以參考下2023-12-12Java隨機值設(shè)置(java.util.Random類或Math.random方法)
在編程中有時我們需要生成一些隨機的字符串作為授權(quán)碼、驗證碼等,以確保數(shù)據(jù)的安全性和唯一性,這篇文章主要給大家介紹了關(guān)于Java隨機值設(shè)置的相關(guān)資料,主要用的是java.util.Random類或Math.random()方法,需要的朋友可以參考下2024-08-08Java技巧函數(shù)方法實現(xiàn)二維數(shù)組遍歷
這篇文章主要介紹了Java技巧函數(shù)方法實現(xiàn)二維數(shù)組遍歷,二維數(shù)組遍歷,每個元素判斷下是否為偶數(shù),相關(guān)內(nèi)容需要的小伙伴可以參考一下2022-08-08