最近看到一些介紹這兩個注解的帖子,有一些說的不夠準確,所以在此記錄一下
如果要使用 @JsonFormat 這個注解的話,需要在專案中添加 jackson 相關的依賴包
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
如果要使用 @DateTimeFormat 這個注解的話,需要在專案中添加 springframework 相關的依賴包
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.9</version>
</dependency>
注:SpringBoot的 spring-boot-start-web 下已經包含了jackson的相關依賴,spring-boot-starter-freemarker 下已經包含了springframework的相關依賴,不需要額外添加,我這里使用的開發工具是idea,使用Maven Helper這個插件可以看pom依賴關系樹
- Maven Helper 插件

- 使用Maven Helper查看依賴關系樹
jackson

springframework

大家可以去這個網站搜索想要的依賴:https://mvnrepository.com

@JsonFormat(pattern = “yyyy-MM-dd HH:mm:ss”,timezone = “GMT+8”)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime userCreateDate;
將后端回傳給前端的日期時間進行格式化,pattern為轉換后的格式,timezone為日期時間的時區
在國內默認時區使用的是CST時區,兩者相差8小時,這里時區為設定時區為上海時區
@DateTimeFormat(pattern = “yyyy-MM-dd HH:mm:ss”)
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime userCreateDate;
將前端傳給后端的日期時間進行格式化,pattern為轉換后的格式
總結
POST請求,我們一般會用@RequestBody接收JSON物件,如果物件里面有日期時間型別資料的話,我們可以使用 @JsonFormat 注解進行格式化,它既可以對出參進行格式化,也可以對入參進行格式化
GET請求引數都是拼接在URL后面的,則需要使用@DateTimeFormat對入參進行格式化,放到@RequestBody修飾的物件里面是無效的
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/292698.html
標籤:其他
下一篇:Eclipse 使用和問題總結
