spring mvc date format with form:input

Ste*_*nko 19 java spring jpa jstl spring-mvc

我有hibernate实体和bean:

@Entity
public class GeneralObservation {
    @DateTimeFormat(pattern = "dd/MM/yyyy")
    Date date;

    @Column
    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}
Run Code Online (Sandbox Code Playgroud)

我也有

@InitBinder
protected void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    binder.registerCustomEditor(Date.class, new CustomDateEditor(
            dateFormat, false));
}
Run Code Online (Sandbox Code Playgroud)

        form:input
                id = "datepicker"
                name="date"
                itemLabel="date"
                path="newObservation.date"
Run Code Online (Sandbox Code Playgroud)

当我转到我的网址时,我看到:

我的表格

如何强制它具有mm/DD/yyyy格式?感谢名单

yna*_*ame 23

您可以使用fmt:formatDate jstl标记:

<fmt:formatDate value="${yourObject.date}" var="dateString" pattern="dd/MM/yyyy" />
<form:input path="date" value="${dateString} .. />
Run Code Online (Sandbox Code Playgroud)


Ste*_*nko 7

解决方案是将
<mvc:annotation-driven/> mvc-dispatcher-servlet.xml和xmlns:mvc ="http://www.springframework.org/schema/mvc"放到xml文件的开头.


小智 5

在我的代码中,我以这种方式使用活页夹:

@InitBinder
public void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    dateFormat.setLenient(false);
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
Run Code Online (Sandbox Code Playgroud)