• 后台日期类型数据接收到前端数据后报Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'错误


    三种解决办法:

    解决方法一:
    在接收的字段上面,添加下面的注解 就可以了

    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") //返回时间类型(使用JsonFormat时,一定要加上timezone ,否则会导致前端显示时间和数据库时间差12小时)
    
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") //接收时间类型
    
    private Date startTime;
    

    解决方法二(局部解决方法):
    @Controller
    public class UserController{

    @RequestMapping(value="/xxxxxxx")
    public String recive(Date startTime){
    	*********
    	return "";
    }
    
        //只需要加上下面这段即可,注意不能忘记注解
    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
    	//转换日期
    	DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd"); //到日
    	binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
    }
    

    }

    解决方法三(全局解决方法):
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import org.springframework.beans.propertyeditors.CustomDateEditor;
    import org.springframework.web.bind.WebDataBinder;
    import org.springframework.web.bind.support.WebBindingInitializer;
    import org.springframework.web.context.request.WebRequest;

      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));
      	}
      }
  • 相关阅读:
    匿名函数
    Python基础练习题5
    for循环实现一个注册小案例
    Python基础练习题4
    Python集合
    Python基础练习题3
    Python 元组和字典
    Python PEP8规范与python之禅
    Python基础练习题2
    常见的排序之冒泡排序
  • 原文地址:https://www.cnblogs.com/liyibo/p/15015974.html
Copyright © 2020-2023  润新知