栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Failed to convert value of type ‘java.lang.String‘ to required type ‘java.util.Date‘&&springboot接收时间

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Failed to convert value of type ‘java.lang.String‘ to required type ‘java.util.Date‘&&springboot接收时间

在使用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,如有人知其缘由,欢迎指教!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/605635.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号