【问题标题】:spring mvc date format with form:input带有表单的spring mvc日期格式:输入
【发布时间】:2013-08-12 08:56:08
【问题描述】:

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

我也有

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

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

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

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

【问题讨论】:

  • @DateTimeFormat(pattern = "dd/MM/yyyy")new SimpleDateFormat("dd/MM/yyyy") 都使用 dd/MM/yyyy。您是否尝试将它们更改为mm/DD/yyyy
  • 不,这无济于事,因为 form:input 不允许明确输入默认值。
  • 你用过mvc:annotation-driven吗?
  • 不,我应该把 mvc:annotation-driven 放在哪里?

标签: java spring spring-mvc jpa jstl


【解决方案1】:

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

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

【讨论】:

  • 试试:$(document).ready(function(){ $(function() { $("#datepicker").datepicker({ changeMonth : true, changeYear : true, dateFormat : 'dd /MM/yyyy' }); });
  • 我不需要日期选择器。日期格式不是我所期望的。
【解决方案2】:

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

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

【讨论】:

  • 为什么会出现在 -ve 中?
【解决方案3】:

解决办法是把
&lt;mvc:annotation-driven/&gt; 到 mvc-调度程序-servlet.xml 还有 xmlns:mvc="http://www.springframework.org/schema/mvc" 到xml文件的开头。

【讨论】:

  • 如果我不使用 xml 作为 dispatcher 怎么办?
【解决方案4】:

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

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

【讨论】:

  • 是的,对于不实陈述,我们深表歉意。在我的应用程序中,我遇到了同样的情况,但日期格式是正确的(就像我在字段前的 DateTimeFormat 注释中指定的那样)。不仅字段的表示是正确的:我没有 @InitBinder 方法并且所有工作都正确。也许我有更新版本的 spring 库(3.1.1.RELEASE)?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-10
  • 1970-01-01
  • 2013-02-01
  • 1970-01-01
  • 2015-03-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多