java中多种格式的日期绑定器
如何在java中多种格式的日期绑定器,java,spring,date,spring-mvc,Java,Spring,Date,Spring Mvc,如何在InitBinder中的CustomEditor中提供多种格式的日期 这是我的活页夹里面的控制器 @InitBinder public void binder(WebDataBinder binder) { binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("dd-MM-yyyy"), true)); } 现在我还需要格式日期mm/dd/yy
InitBinder
中的CustomEditor
中提供多种格式的日期
这是我的活页夹里面的控制器
@InitBinder
public void binder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class,
new CustomDateEditor(new SimpleDateFormat("dd-MM-yyyy"), true));
}
现在我还需要格式日期mm/dd/yyyy
,即两种格式都需要。如何实现这一点?根据,每个属性路径只支持一个已注册的自定义编辑器
这意味着(您可能已经知道),您将无法将两个自定义编辑器绑定到同一个类。简单地说,你不能有:
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
s
例如,考虑此自定义<代码> DateFormat < /代码>(以下),它可以< <强> >解析> <代码>日期>代码> 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;
}
}
尊敬的先生,根据以下示例:,您实际上可以注册多个自定义编辑器。对不起。经过更多的关注,我意识到这个问题和你的答案是关于一个属性的一个编辑器
binder.registerCustomEditor(Date.class, new CustomDateEditor(new MyDateFormat(), true));