问题
无法请求到后台,后台报错:[Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property
:
2023-10-02T09:26:16.069+08:00 WARN 14296 --- [p-nio-80-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public com.tiku.common.bean.ResultBean com.tiku.controller.manger.BookController.list(com.tiku.domain.query.BookQuery) with 2 errors: [Field error in object 'bookQuery' on field 'beginTime': rejected value [2000-12-12 12:12:12]; codes [typeMismatch.bookQuery.beginTime,typeMismatch.beginTime,typeMismatch.java.time.LocalDateTime,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [bookQuery.beginTime,beginTime]; arguments []; default message [beginTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property 'beginTime'; Failed to convert from type [java.lang.String] to type [java.time.LocalDateTime] for value [2000-12-12 12:12:12]]] [Field error in object 'bookQuery' on field 'endTime': rejected value [2020-12-12 12:12:12]; codes [typeMismatch.bookQuery.endTime,typeMismatch.endTime,typeMismatch.java.time.LocalDateTime,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [bookQuery.endTime,endTime]; arguments []; default message [endTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property 'endTime'; Failed to convert from type [java.lang.String] to type [java.time.LocalDateTime] for value [2020-12-12 12:12:12]]] ]
方式一
在application.yml中添加:
spring:
mvc:
format:
date-time: yyyy-MM-dd HH:mm:ss
#时间格式:返回格式化日期
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
方式二
在类的属性上添加注解:
// 接收时间类型
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
//返回时间类型
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private LocalDateTime beginTime;
说明:
- @DateTimeFormat :该注解自动会解析处理,会把字符串类型 按照格式yyyy-MM-dd HH:mm:ss 转换成时间类型
- @JsonFormat:该注解是从数据库查询出来,返回到页面的的转换. 把时间类型 转换成JSON格式类型,前提取出进行展示.