Java 異常 Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date'


查詢時發送給服務器的日期的字符串格式:yyyy-MM-dd HH:mm:ss

服務器接收到日期的字符串之后,向 MySQL 數據庫發起查詢時,因為沒有指定日期時間格式,導致字符串數據不能正確地轉換為日期而產生的錯誤:

1 2019-12-05 17:43:55.215  WARN 1460 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors
2 Field error in object 'billsVo' on field 'endTime': rejected value [2019-12-05 00:00:00]; codes [typeMismatch.billsVo.endTime,typeMismatch.endTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [billsVo.endTime,endTime]; arguments []; default message [endTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'endTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2019-12-05 00:00:00'; nested exception is java.lang.IllegalArgumentException]
3 Field error in object 'billsVo' on field 'startTime': rejected value []; codes [typeMismatch.billsVo.startTime,typeMismatch.startTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [billsVo.startTime,startTime]; arguments []; default message [startTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'startTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value ''; nested exception is java.lang.IllegalArgumentException]]

解決方法:在相應的屬性上使用 @DateTimeFormat 注解,並指定格式,見第 14 或 16 行:

 1 import java.util.Date;
 2 
 3 import org.springframework.format.annotation.DateTimeFormat;
 4 
 5 import lombok.AllArgsConstructor;
 6 import lombok.Data;
 7 import lombok.NoArgsConstructor;
 8 
 9 @NoArgsConstructor // 無參構造方法
10 @AllArgsConstructor // 有參構造方法
11 @Data // Getters、Setters、toString() 等方法
12 public class BillsVo {
13 
14     @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
15     private Date startTime;
16     @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
17     private Date endTime;
18 }

 

順便一說,如果要指定服務器端返回給客戶端的日期的 JSON 格式:

可以在相應的類的屬性上使用 @JsonFormat 注解:

1     @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
2     @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
3     private Date billtime;

如果是 Spring Boot 項目,也可以在 application.yml 文件中指定:

1 spring:
2   jackson:
3     date-format: yyyy-MM-dd HH:mm:ss
4     time-zone: GMT+8

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM