【问题标题】:Date binder of multiple formats in javajava中多种格式的日期绑定器
【发布时间】:2014-08-09 14:42:08
【问题描述】:

如何在CustomEditor 中在InitBinder 中提供多种格式的日期?

这是我在控制器中的活页夹。

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

现在我还想要mm/dd/yyyy 格式的日期,即需要两种 格式。如何做到这一点?

【问题讨论】:

    标签: java spring date spring-mvc


    【解决方案1】:

    根据Spring documentation of DataBinder#registerCustomEditor,每个属性路径只支持一个注册的自定义编辑器。

    这意味着(您可能已经知道),您将无法将两个自定义编辑器绑定到同一个类。简而言之,您不能拥有:

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

    但是,您可以注册自己的 DateFormat 实现,它会按照您的意愿运行,这取决于您需要的两个 SimpleDateFormats。

    例如,考虑这个自定义的DateFormat(如下),它可以解析 Dates 是"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;
        }
    }
    

    然后,您只需将Date.class 绑定到基于MyDateFormat 实例构造的CustomDateEditor,如下所示:

    binder.registerCustomEditor(Date.class, new CustomDateEditor(new MyDateFormat(), true));
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    相关资源
    最近更新 更多