springMVC中的日期格式的转化

时间:2019-06-12
本文章向大家介绍springMVC中的日期格式的转化,主要包括springMVC中的日期格式的转化使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、jsp页面传递到controller的日期

如果实体类中封装的日期类型为Date,而jsp页面中的传来的为string类型,这个时候后台就会报错,出现400错误,原因是前后端的数据类型不一致。要将jsp页面中传过来的数据类型转化为Date,如下方法:

方法一:在对应的controller中加入代码:

  @InitBinder
    protected void init(HttpServletRequest request, ServletRequestDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

方法二:在对应的controller中加入代码:

  @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); // true:允许输入空值,false:不能为空值

    }

 方法三:在实体类中进行数据绑定

@DateTimeFormat(pattern="yyyy-MM-dd")
private Date borth;

二:后台Date类型的数据传到jsp页面 转化为String

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:formatDate value="${train.endtime }" pattern="yyyy-MM-dd HH:mm:ss"/>

原文地址:https://www.cnblogs.com/wanerhu/p/11009566.html