【问题标题】:Grails 2.1 and CustomDateEditor doesn't seem to workGrails 2.1 和 CustomDateEditor 似乎不起作用
【发布时间】:2012-10-08 15:23:08
【问题描述】:

我在 Grails 2.1.0 中使用 CustomDateEditor 时遇到问题

我想要达到的目标:

日期类现在呈现为 08/10/2013 00:00:00 CEST 但我想将格式更改为 08/10/2013(dd/MM/yyyy 格式)

到目前为止我做了什么:

resource.groovy

beans = {
    customPropertyEditorRegistrar(myutil.CustomPropertyEditorRegistrar)
}

myutil.CustomPropertyEditorRegistrar

package myutil

import org.springframework.beans.PropertyEditorRegistrar
import org.springframework.beans.PropertyEditorRegistry
import org.springframework.beans.propertyeditors.CustomDateEditor
import java.text.SimpleDateFormat

public class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {
    public void registerCustomEditors(PropertyEditorRegistry registry) {
        registry.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat('dd/MM/yyyy'), true)) //this doesn't work
        registry.registerCustomEditor(java.math.BigDecimal.class, new CurrencyPropertyEditor()) //this work so at least the registerCustomEditors method is invoked
    }
}

正如您在我的代码中看到的,有一个 CurrencyPropertyEditor 可以正常工作,所以我在这里很困惑.. 发生了什么?

我四处搜索,似乎我的代码没有错误,但仍然无法正常工作。

提前感谢您的任何提示。

【问题讨论】:

  • 嗯.. 不知道,为什么 2 downvote.. 这个问题有那么糟糕吗?

标签: spring date grails grails-2.1


【解决方案1】:

如果 this 的范围是以您自己的自定义格式呈现日期,那么使用g:formatDate 标签不是更好吗? 类似的东西:

 <g:formatDate format="dd/MM/yyyy" date="${date}"/>

查看formatDate 文档

【讨论】:

  • 是的,这很容易,但我想使用脚手架模板,所以我无法更改 AFAIK,除此之外,问题仍然存在
  • 您是否在文档中看到过它formatName(可选) - 使用此键从默认的 MessageSource / ResourceBundle(i18n/*.properties 文件)中查找格式。如果 format 和 formatName 为空,则使用 'default.date.format' 键查找格式。如果未指定密钥,则默认为 'yyyy-MM-dd HH:mm:ss z' 我从未使用过它,但是您可以尝试将该属性放在配置文件中,这样您就没有只改变一个属性:) 希望它有效
  • 谢谢,问题解决了。我仍然很好奇为什么我可以将属性编辑器与 BigDecimal 一起使用,但不能与 Date 一起使用。如果没人能回答,我会接受你的回答。
  • 问题是propertyEditor 不是用于渲染的东西...如果您想将日期放入输入字段中,则使用它...属性编辑器是一个知道如何操作的对象将对象(在本例中为日期)转换为字符串(使用 DateFormatter)以及如何从字符串创建日期。过去,我将它与我的应用程序的域类一起使用(Grails 会自动使用它)。为此,我编写了一个 propertyEditor,它在 String 中转换域类(获取 id)并从 String 创建我的域对象(使用该 id 查询 db)。
  • 在评论中解释起来并不容易。但是如果你很好奇,你可以在 javadoc docs.oracle.com/javase/1.4.2/docs/api/java/beans/… 和 SpringMVC 文档中找到很多东西;)
猜你喜欢
  • 1970-01-01
  • 2023-03-27
  • 2015-07-06
  • 2016-11-24
  • 2014-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多