`
MafiaDada
  • 浏览: 25515 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Register multiple date format for binding properities

阅读更多
Grails可以自动把params里面的参数绑定到domain class。有些时候为了能够绑定自定义的日期格式,例如"yyyy-MM-dd",需要register一个自己的CustomDateEditor。

有时候还有需求要绑定多种格式的日期,例如"yyyy/MM/dd"、"yyyy-MM-dd HH:mm:ss"等等,这时候就需要一个支持多种日期格式的CustomDateEditor,解决方法如下:

1. 新建一个MultipleDateEditor.groovy
package com.myapp

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.util.Date;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.util.StringUtils;

/**
 * Property editor for java.util.Date, supporting multiple custom input formats
 * and custom output formats.  This class utilizes DateUtils and
 * DateFormatUtils of Apache Commons Lang, and has been tested for version 2.4
 * but may work with older versions.
 *
 * It should be noted that the date input formats should be inserted into the
 * array based on the length of the string, longest to shortest.
 *
 * This is not meant to be used as system PropertyEditor but rather as
 * locale-specific date editor within custom controller code, parsing
 * user-entered number strings into Date properties of beans and rendering
 * them in the UI form.
 *
 * In web MVC code, this editor will typically be registered with
 * binder.registerCustomEditor calls in a custom initBinder method.
 *
 * @author jpreston
 * @see java.beans.PropertyEditorSupport
 * @see java.util.Date
 * @see org.apache.commons.lang.time.DateUtils
 * @see org.apache.commons.lang.time.DateFormatUtils
 */
public class MultipleDateEditor extends PropertyEditorSupport {

    /**
     * The date format used to format a Date into a String
     */
    public final static String DEFAULT_OUTPUT_FORMAT = "dd/mm/yyyy";
    /**
     * The date formats used to parse a String into a Date
     */
    public final static String[] DEFAULT_INPUT_FORMATS = [
        "dd/mm/yyyy hh:mm:ss",
        "dd-mm-yyyy hh:mm:ss",
        "dd/mm/yy hh:mm:ss",
        "dd-mm-yy hh:mm:ss",
        "dd/mm/yyyy",
        "dd-mm-yyyy",
        "dd/mm/yy",
        "dd-mm-yy"
    ];
    /** The format used to convert a Date into a String */
    private String outputFormat;
    /** An array of date formats used to convert a String into a Date */
    private String[] inputFormats;
    /** Allow empty strings to be parsed instead of treated as null */
    private boolean allowEmpty;

    /**
     * Create a new MultipleDateEditor instance using the default values
     */
    public MultipleDateEditor() {
        outputFormat = MultipleDateEditor.DEFAULT_OUTPUT_FORMAT;
        inputFormats = MultipleDateEditor.DEFAULT_INPUT_FORMATS;
        allowEmpty = false;
    }

    /**
     * Create a new MultipleDateEditor instance using the given date
     * input and output formats.
     *
     * The "allowEmpty" parameter states if an empty String should be allowed for
     * parsing, i.e. get interpreted as null value. Otherwise, an
     * IllegalArgumentException gets thrown in that case.
     *
     * @param outputFormat The format used to convert a Date into a String
     * @param inputFormats An array of date formats used to convert a String into a Date
     */
    public MultipleDateEditor(String outputFormat, String[] inputFormats) {
        this.outputFormat = outputFormat;
        this.inputFormats = inputFormats;
        allowEmpty = false;
    }

    /**
     * Create a new MultipleDateEditor instance using the given date
     * input and output formats.
     *
     * The "allowEmpty" parameter states if an empty String should be allowed for
     * parsing, i.e. get interpreted as null value. Otherwise, an
     * IllegalArgumentException gets thrown in that case.
     *
     * @param outputFormat The format used to convert a Date into a String
     * @param inputFormats An array of date formats used to convert a String into a Date
     * @param allowEmpty Allow empty strings to be parsed instead of treated as null
     */
    public MultipleDateEditor(String outputFormat, String[] inputFormats,
            boolean allowEmpty) {
        this.outputFormat = outputFormat;
        this.inputFormats = inputFormats;
        this.allowEmpty = allowEmpty;
    }

    /**
     * Format the Date as String, using the specified outputFormat.
     *
     * If allowEmpty is true (default is false), and the Date is null, an empty
     * String will be returned; otherwise it is possible that a NPE or other
     * parsing exception will occur.
     *
     * @return The string value of the Date
     */
    @Override
    public String getAsText() {
        if (allowEmpty && getValue() == null) {
            return "";
        }

        return DateFormatUtils.format((Date) getValue(), outputFormat);
    }

    /**
     * Parse the Date from the given text, using the first matching date format
     * specified in the inputFormats array.
     *
     * If no matching input format is found, an IllegalArgumentException is thrown.
     *
     * If allowEmpty is true (default is false), and the String is null, the Date
     * will be interpreted as null; otherwise an IllegalArgumentException is thrown.
     *
     * @param text the text to convert into a java.util.Date
     * @throws IllegalArgumentException thrown if no matching format is found
     */
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        try {
            if (StringUtils.hasText(text)) {
                setValue(DateUtils.parseDate(text, inputFormats));
            } else {
                if (allowEmpty) {
                    setValue(null);
                } else {
                    throw new IllegalArgumentException(
                            "The text specified for parsing is null");
                }
            }
        } catch (ParseException ex) {
            throw new IllegalArgumentException("Could not parse text ["
                    + text + "] into any available date input formats", ex);
        }
    }

    /**
     * If allowEmpty is true (default is false), and the Date is null, an empty
     * String will be returned; otherwise it is possible that a NPE or other
     * parsing exception will occur.
     *
     * If allowEmpty is true (default is false), and the String is null, the Date
     * will be interpreted as null; otherwise an IllegalArgumentException is thrown.
     *
     * @return whether empty strings are allowed
     */
    public boolean isAllowEmpty() {
        return allowEmpty;
    }

    /**
     * If allowEmpty is true (default is false), and the Date is null, an empty
     * String will be returned; otherwise it is possible that a NPE or other
     * parsing exception will occur.
     *
     * If allowEmpty is true (default is false), and the String is null, the Date
     * will be interpreted as null; otherwise an IllegalArgumentException is thrown.
     *
     * @param allowEmpty whether empty strings should be allowed
     */
    public void setAllowEmpty(boolean allowEmpty) {
        this.allowEmpty = allowEmpty;
    }

    /**
     * Get the date formats used to parse a String into a Date
     *
     * @return The date formats used to parse a String into a Date
     */
    public String[] getInputFormats() {
        return inputFormats;
    }

    /**
     * Set the date formats used to parse a String into a Date.  It should be
     * noted that the date formats should be inserted into the array based
     * on the length of the format, longest to shortest.
     *
     *
     * @param inputFormats The date formats used to parse a String into a Date
     */
    public void setInputFormats(String[] inputFormats) {
        this.inputFormats = inputFormats;
    }

    /**
     * Get the format used to convert a Date into a String
     *
     * @return The format used to convert a Date into a String
     */
    public String getOutputFormat() {
        return outputFormat;
    }

    /**
     * Set the format used to convert a Date into a String
     *
     * @param outputFormat The format used to convert a Date into a String
     */
    public void setOutputFormat(String outputFormat) {
        this.outputFormat = outputFormat;
    }
}


2. 新建MultipleDateEditorRegistrar.groovy
package com.myapp

import org.springframework.beans.PropertyEditorRegistrar
import org.springframework.beans.PropertyEditorRegistry

/**
 * binding date properties with customer format
 * "yyyy-MM-dd HH:mm:ss"
 * "yyyy-MM-dd HH:mm"
 * "yyyy-MM-dd"
 */
public class MultipleDateEditorRegistrar implements PropertyEditorRegistrar {
  public void registerCustomEditors(PropertyEditorRegistry registry) {
      registry.registerCustomEditor(Date.class, 
new MultipleDateEditor("yyyy-MM-dd HH:mm:ss",
              ["yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd"] as String[], true));
  }
}


3. 注册到spring beans
beans = {
        customPropertyEditorRegistrar(com.nazuche.MultipleDateEditorRegistrar)
}



Reference: http://forum.springsource.org/showthread.php?78118-Multiple-Date-Formats-in-a-Form

分享到:
评论

相关推荐

    JAXB_Java Architecture For XML Binding

    Java Architecture for XML Binding (JAXB) 是Java平台上的一个标准技术,它允许程序开发者将XML文档与Java对象之间进行绑定,实现XML数据的序列化和反序列化。JAXB是Java SE和Java EE环境中的一部分,提供了高效且...

    jaxb 2.0 java architecture for xml binding

    THE Java™Architecture for XML Binding (JAXB) provides a fast and convenient way to bind between XML schemas and Java representations, making it easy for Java developers to incorporate XML data and ...

    C#应用BindingSource实现数据同步的方法

    在C#编程中,`BindingSource`组件是一个非常重要的工具,用于在UI(用户界面)控件和数据源之间建立数据绑定。它提供了一种方便的方式来管理数据的显示、编辑和同步,尤其是在涉及多个控件与同一数据源交互的场景中...

    WPF中StringFormat的用法

    在 WPF 中,`StringFormat` 可以在 `Binding` 对象中设置,以控制绑定到 UI 元素(如 `TextBox`)的数据如何显示。其基本语法类似于 C# 中的 `string.Format` 方法,但使用 `{}` 代替 `{0}` 这样的索引表示。 ### ...

    C# MVVM Binding demo

    <DataGridTextColumn Header="Publication Date" Binding="{Binding PublicationDate, StringFormat='{}{0:yyyy-MM-dd}'}" /> <Button Content="Add Book" Command="{Binding AddBookCommand}" /> ``` **视图...

    基于BindingSource的WinForm开发

    在Windows Forms应用开发中,`BindingSource`组件扮演着至关重要的角色,它是连接数据源与UI控件的关键组件。本文将深入探讨`BindingSource`在WinForm开发中的使用,包括其基本概念、功能、以及如何实现主细表绑定、...

    win32-ia-32-48_binding.node插件去掉node不报错

    win32-ia-32-48_binding.node插件去掉node不报错win32-ia-32-48_binding.node插件去掉node不报错win32-ia-32-48_binding.node插件去掉node不报错win32-ia-32-48_binding.node插件去掉node不报错win32-ia-32-48_...

    WPF的binding代码实例

    在这个“WPF的binding代码实例”中,我们将深入探讨几个基础的绑定用法,帮助开发者更好地理解和应用这一特性。 1. **基本绑定语法** WPF中的数据绑定通常使用`{Binding}`标记来实现。例如,一个`TextBlock`控件的...

    Port Binding Failed(处理方案).md

    Port Binding Failed(处理方案).md

    wpf binding 的两种方法

    2. **创建绑定(Binding)**:接着,为需要绑定的控件属性创建一个`Binding`对象,指定要绑定的数据源属性。 ```csharp myTextBlock.SetBinding(TextBlock.TextProperty, new Binding("MyDataProperty")); ``` ...

    Android支持JAXB(Java Architecture for XML Binding)

    Android支持JAXB(Java Architecture for XML Binding) JAXB(Java Architecture for XML Binding)是Java领域中的一项标准技术,能够根据XML Schema生成Java类,并将XML实例文档反向生成Java对象树。JAXB提供了将...

    win32-x64-51-57-59-64-67-72-79-83-binding.node多版本.zip

    标题中的"win32-x64-51-57-59-64-67-72-79-83-binding.node多版本.zip"揭示了这是一份包含多个版本的`binding.node`模块的压缩包。`binding.node`在IT行业中,特别是Node.js的上下文中,是一个关键的概念,它是Node....

    Emacs Key Binding for Delphi 7

    Emacs Key binding for Delphi 7(親測),Delphi xe2(也可以用) 使用方法: 使用delphi安裝MyEmacs組件即可, 每次打開delphi時,需要在Key Mapping中去掉勾選【Buffer List】這個Module即可, 里面有一些我自己的快捷...

    Data Binding with Windows Forms 2.0

    Data Binding with Windows Forms 2.0: Programming Smart Client Data Applications with .NET By Brian Noyes ............................................... Publisher: Addison Wesley ...

    EFI Howto:Driver binding的实质

    EFI驱动模型与Windows驱动模型的比较和Driver Binding的实现 本文主要介绍了EFI驱动模型的概念,特别是Driver Binding的实现过程,同时借鉴了Windows驱动模型的一些概念,以便更好地理解EFI驱动模型。 首先,我们...

    MVVM+ViewBinding+Kotlin入门

    在Android开发领域,MVVM(Model-View-ViewModel)架构、ViewBinding以及Kotlin语言的组合,已经成为现代应用开发的标准工具和技术栈。本教程将帮助初学者了解这三种技术的基本概念,以及如何将它们整合到实际项目中...

    深入解析:Java中JAXB(Java Architecture for XML Binding)实现机制

    JAXB,即Java Architecture for XML Binding,是Java EE的一部分,提供了一种将XML数据结构化为Java对象的机制,以及反向的绑定过程。本文将深入探讨JAXB的实现原理、使用方法和最佳实践。 JAXB为Java开发者提供了一...

    beans-binding-talk

    ### Beans Binding:经验和技巧 #### 一、简介 **Beans Binding** 是一项强大的技术,它允许开发者轻松地在 Java 应用程序中的不同组件之间建立数据绑定。这项技术基于 JSR 295(Java Specification Request 295)...

    自定义android开发MVP+ViewBinding架构Demo

    ViewBinding是Google官方推荐的一种替代findViewById的方法,可以更方便地处理UI元素和业务逻辑之间的绑定。在这个"自定义android开发MVP+ViewBinding架构Demo"中,我们将深入探讨这两个技术的结合使用。 首先,MVP...

    Java API for JSON Binding (JSON-B).zip

    Java API for JSON Binding (JSON-B) 是Java平台上的一个标准API,它提供了自动将Java对象绑定到JSON(JavaScript Object Notation)格式的能力。这个API在Java EE 8及更高版本中被引入,作为JSR 367的一部分,旨在...

Global site tag (gtag.js) - Google Analytics