SpringBoot 日期时间参数匹配问题

前端使用Element-UI的 el-time-picker,设置value-format=timestamp

前端打印参数如下,timestamp类型

image.png

Chrome报错截图:

400错误

image.png

后台错误:

  1. 2019-06-24 08:39:53.554 WARN 25492 --- [nio-8005-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors
  2. Field error in object 'dayEvent' on field 'endTime': rejected value [1561336773000]; codes [typeMismatch.dayEvent.endTime,typeMismatch.endTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [dayEvent.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 '1561336773000'; nested exception is java.lang.IllegalArgumentException]
  3. Field error in object 'dayEvent' on field 'startTime': rejected value [1561334400000]; codes [typeMismatch.dayEvent.startTime,typeMismatch.startTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [dayEvent.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 '1561334400000'; nested exception is java.lang.IllegalArgumentException]]

核心错误:

Failed to convert from type [java.lang.String] to type [java.util.Date] for value ‘1561336773000’; nested exception is java.lang.IllegalArgumentException
无法将字符串类型的值转换为Date类型

解决方法:

1. 前端处理,修改参数格式为”yyyy-MM-dd HH:mm:ss”

2. 后端Controller 增加自定义处理

  1. /**
  2. * 自定义时间格式处理
  3. */
  4. @InitBinder
  5. public void initBinder(WebDataBinder binder) {
  6. //转换日期
  7. DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  8. // CustomDateEditor为自定义日期编辑器
  9. binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
  10. }

延伸学习:

  1. 了解Spring参数处理机制
  2. 了解ElementUI value-format 参数问题