Java spring mvc 日期格式与表单:输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18163404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:57:17  来源:igfitidea点击:

spring mvc date format with form:input

javaspringspring-mvcjpajstl

提问by Stepan Yakovenko

I have hibernate entity and a bean:

我有休眠实体和一个 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;
    }
}

also I have

我也有

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

and

        form:input
                id = "datepicker"
                name="date"
                itemLabel="date"
                path="newObservation.date"

When I go to my url I see:

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

my form

我的表格

How can I force it to have mm/DD/yyyy format? Thanx

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

采纳答案by Stepan Yakovenko

The solution is to put
<mvc:annotation-driven/>to mvc-dispatcher-servlet.xml and also xmlns:mvc="http://www.springframework.org/schema/mvc" to the begining of xml file.

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

回答by yname

You can use fmt:formatDate jstl tag:

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

<fmt:formatDate value="${yourObject.date}" var="dateString" pattern="dd/MM/yyyy" />
<form:input path="date" value="${dateString} .. />

回答by Oibaf it

in my code I use the binder in this way:

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

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

回答by Hassen Ch.

In HTML5 there is input type="date", same thing in Spring (Chrome , Opera, and I this Safary too, but not yet in Firefox

在 HTML5 中有 input type="date",在 Spring 中也是一样的(Chrome ,Opera,我也是这个 Safary,但在 Firefox 中还没有

<form:input type="date" ... >