java中多种格式的日期绑定器

use*_*230 5 java spring date spring-mvc

我怎样才能给日期的多种格式中CustomEditorInitBinder

这是控制器内部的活页夹.

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

现在我也希望格式化日期mm/dd/yyyy,即两种格式都需要.怎么做到这一点?

ccj*_*mne 7

按照DataBinder的#registerCustomEditor的Spring文档,支持每属性路径只有一个单一的注册自定义编辑器.

这意味着(您可能已经知道),您将无法将两个自定义编辑器绑定到同一个类.简单来说,你不能拥有:

binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("dd-MM-yyyy"), true));
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("dd/mm/yyyy"), true));
Run Code Online (Sandbox Code Playgroud)

但是,您可以根据自己的需要注册自己的实现DateFormat,并依赖于您需要SimpleDateFormat的两个.

例如,考虑这个自定义DateFormat(下面),它可以解析 Date s "dd-MM-yyyy""mm/dd/yyyy"格式:

public class MyDateFormat extends DateFormat {

    private static final List<? extends DateFormat> DATE_FORMATS = Arrays.asList(
        new SimpleDateFormat("dd-MM-yyyy"),
        new SimpleDateFormat("mm/dd/yyyy"));

    @Override
    public StringBuffer format(final Date date, final StringBuffer toAppendTo, final FieldPosition fieldPosition) {
        throw new UnsupportedOperationException("This custom date formatter can only be used to *parse* Dates.");
    }

    @Override
    public Date parse(final String source, final ParsePosition pos) {
        Date res = null;
        for (final DateFormat dateFormat : DATE_FORMATS) {
            if ((res = dateFormat.parse(source, pos)) != null) {
                return res;
            }
        }

        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您只需要绑定Date.classCustomDateEditor构造的实例MyDateFormat,如下所示:

binder.registerCustomEditor(Date.class, new CustomDateEditor(new MyDateFormat(), true));
Run Code Online (Sandbox Code Playgroud)