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

时间:2014-08-09 14:42:08

标签: java spring date spring-mvc

如何在CustomEditor的{​​{1}}中提供多种日期格式?

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

InitBinder

现在我也想要格式@InitBinder public void binder(WebDataBinder binder) { binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("dd-MM-yyyy"), true)); } 的日期,即两种格式都需要。怎么做到这一点?

1 个答案:

答案 0 :(得分:7)

根据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注册自己的SimpleDateFormat实施方案。

例如,考虑一下这个自定义DateFormat(下方),它可以在<{1}}或Date解析 "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实例上构建的CustomDateEditor,如下所示:

MyDateFormat
相关问题