springboot 提交时间字符串报错 Failed to convert property value of type 'java.lang.String' to required 'Date'

springboot 提交时间字符串匹配 Date 报错: Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date'

解决方法:

在实体类的属性上加上 @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") 注解。

如:  
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Column(name = "LOGIN_TIME")
private Date loginTime;

 

刚才发现,如果转换的时间格式定义为 "yyyy-MM-dd HH:mm:ss",

那页面传到后台的字符串是这种格式的:"2019-01-31 14:33",后台还是会报错,因为字符串里没有 秒 的数据。

 

-----------------------------------------------------------------

另一种方法是在 controller 里加一个方法:

// 格式化页面传递到后台的 时间字符串 为 Date 类型
    @InitBinder
    protected void init( HttpServletRequest request, ServletRequestDataBinder binder ) {
        SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss" );
        dateFormat.setLenient( false );
        binder.registerCustomEditor( Date.class, new CustomDateEditor( dateFormat, false ) );
    }

不过这种 @InitBinder 的方法,在页面提交一个空字符串到后台匹配 date 时会报错。

所以,还是应该使用 @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") 注解匹配后台的 Date 对象。

------------------------------------------

如果新增或修改时间字段时,需要秒都是 00,可以把这个注解写成这样:

@DateTimeFormat( pattern = "yyyy-MM-dd HH:mm" )

 

你可能感兴趣的:(java)