目錄
入參為Date類型時,默認情況下發生了錯誤:
2021-09-01 14:43:19.855 WARN 22940 --- [io-30005-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver :
Resolved [org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: Cannot deserialize value of type `java.util.Date` from String "2021-09-01 14:21:07":
not a valid representation (error: Failed to parse Date value '2021-09-01 14:21:07':
Cannot parse date "2021-09-01 14:21:07": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSX',
parsing fails (leniency? null)); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException:
Cannot deserialize value of type `java.util.Date` from String "2021-09-01 14:21:07": not a valid representation
(error: Failed to parse Date value '2021-09-01 14:21:07': Cannot parse date "2021-09-01 14:21:07":
while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSX', parsing fails (leniency? null))
S.B.版本:2.5.3
入參DTO中定義:
/**
* 發布時間
*/
private Date postTime;
傳入參數為:
“2021-09-01 14:21:07”
點擊提交,發生了開始的錯誤。
解決方案1:單個參數
修改源碼:增加 @DateTimeFormat、@JsonFormat 即可,其實,只需要添加 @JsonFormat 即可。
/**
* 發布時間
*/
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date postTime;
上面的方式,解決了 入參為Date類型轉換的問題。
對於 返回值VO,也需要加上上面的注解才可以確保返回的時間格式:
返回值VO:
1、未添加,默認格式
"postTime": "2021-09-01T14:21:07.000+00:00",
2、添加后的格式
"postTime": "2021-09-01 10:29:30",
@JsonFormat 說明:來自 jackson-annotations-x.x.x.jar 包
解決方案(2):全局
添加配置:
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
即可,入參、返回值,都搞定,都是上面的格式,整個項目有效。
兩種方案的優先級:解決方案1更高
使用解決方案2后,再如下配置入參屬性:
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
private Date postTime;
此時,傳入之前格式的日期出現了異常,並提示:
JSON parse error: Cannot deserialize value of type `java.util.Date` from String "2021-09-02 11:41:10":
expected format "yyyy-MM-dd HH:mm:ss.SSS"; nested exception is ...
此時,入參改為 "postTime":"2021-09-02 11:41:10.123" 即可執行。
返回值也同樣如此。
當然,還有其它解決方案,比如,定制參數、返回值轉換器。
參考文檔:
1、springboot 日期參數前后台轉換問題
https://blog.csdn.net/springdata_/article/details/82629666
2、springboot Date類型入參轉換問題
https://blog.csdn.net/authiur/article/details/104963269
...然后就對問題進行了一次深入挖掘...
3、java 日期格式化-- SimpleDateFormat 的使用。字符串轉日期,日期轉字符串
https://www.cnblogs.com/daxiong225/p/9547078.html