游戲網(wǎng)站建設(shè)多少錢營銷策劃方案模板范文
省流:用@JsonFormat即可
有時(shí)候會(huì)看到入?yún)to里,在時(shí)間類型的變量上用@DateTimeFormat,代碼如下。
public class XXXdto{@DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")private Date startDate;
}
這是為了入?yún)魅掌诟袷降闹?。即前端給后端傳日期,如 {"startDate":"2022-01-01 01:02:02"}。如果沒有@DateTimeFormat,會(huì)報(bào)錯(cuò)。
Invalid JSON input:
Cannot deserialize value of type `java.util.Date` from String "2023-02-01 01:02:03": not a valid representation (error: Failed to parse Date value '2023-02-01 01:02:03': Cannot parse date "2023-02-01 01:02:03": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null));
nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException:
Cannot deserialize value of type `java.util.Date` from String "2023-02-01 01:02:03": not a valid representation (error: Failed to parse Date value '2023-02-01 01:02:03': Cannot parse date "2023-02-01 01:02:03": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null))
根據(jù)報(bào)錯(cuò)信息,while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ',傳入的值日期格式有問題。正確格式:2023-02-01T00:00:00.000+0800,即前端傳參 {"startDate":"2023-02-01T00:00:00.000+0800"}。
所以有人會(huì)用@DataTimeFormat。
但@DataTimeFormat不如@JsonFormat好用。另,如果值是純?nèi)掌?#xff0c;例如2022-01-01,不需要用注解。
@DataTimeFormat用于前端傳后端,@JsonFormat用于后端傳前端,這種說法是錯(cuò)誤的。@JsonFormat前傳后、后傳前都可以用。
@JsonFormat
com.fasterxml.jackson.annotation.JsonFormat;
public class XXXdto{@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")private Date startDate;
}
@DataTimeFormat
org.springframework.format.annotation.DateTimeFormat
public class XXXdto{@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")private Date startDate;
}
@JsonFormat 和 @DateTimeFormat 區(qū)別
@JsonFormat | @DateTimeFormat | |
轉(zhuǎn)換前端傳入后端的時(shí)間格式的值 | √ | √ |
約束后端響應(yīng)前端的時(shí)間類型的值 | √ | × |
數(shù)據(jù)類型(前端提交到后端) | 必須json 用@RequestBody | 必須form表單 不用@RequestBody |
時(shí)區(qū) | √ | × 響應(yīng)給前端的時(shí)間會(huì)比實(shí)際時(shí)間晚8個(gè)小時(shí) |
補(bǔ)充:
1.前端傳值給后端,后端接收到的都是字符串。
2.前端傳日期格式的值,如果形如yyyy-MM-dd,即{"startDate":"2023-01-02"},不需要用@DataTimeFormat和@JsonFormat,框架會(huì)幫你轉(zhuǎn)。
參考
不要在聽大坑們@DateTimeFormat 和 @JsonFormat只是前后端傳參的區(qū)別了_*阿莫西林*的博客-CSDN博客
SpringBoot中時(shí)間格式化的5種方法!