在使用springboot接收Date类型的数据时,报Failed to convert value of type ‘java.lang.String’ to required type 'java.util.Date,或者是LocalDate时出现转换问题的解决方式
@ApiOperation(value = "分页查询所有记录")
@GetMapping("/")
public RespPageBean getAllRecords(@RequestParam(defaultValue = "1") Integer currentPage,
@RequestParam(defaultValue = "10") Integer size,
Date date,String last_next){
return workingService.getAllRecords(currentPage,size,date,last_next);
}
1、添加局部过滤
@InitBinder
public void initBinder(WebDataBinder binder, WebRequest request) {
//转换日期
DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
}
2、全局转换
public class CustomDate implements WebBindingInitializer{
@Override
public void initBinder(WebDataBinder binder, WebRequest request) {
// TODO Auto-generated method stub
//转换日期
DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
}
3、使用注解
@DateTimeFormat 前端给后端
在实体的时间属性(Date,LocalDate,LocalDateTime)上添加,会自动解析处理按照给定格式转换成时间类型,并用setXXX赋值
@JsonFormat 后端给前端
会将从数据库查出的时间类型转换为JSON格式返回给前端展示
@ApiModelProperty(value = "创建时间")
@TableField("createTime")
@JsonFormat(pattern = "yyyy-MM-dd",timezone = "Asia/Shanghai")
@DateTimeFormat(pattern = "yyyy-MM-dd hh:MM:ss")
private LocalDateTime createTime;
pattern
pattren可以为yyyy-MM-dd HH:mm:ss 或者是yyyyMMddHHmmss,
yyyy-MM-dd 都可以
后端接受时间类型的数据时,不要用LocalDateTime类型去接收,笔者试过多次都无法从String转换为LocalDateTime,如有人知其缘由,欢迎指教!



