How can I give multiple formats of date in CustomEditor
in InitBinder
?
Here is my binder inside controller.
@InitBinder
public void binder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class,
new CustomDateEditor(new SimpleDateFormat("dd-MM-yyyy"), true));
}
Now I want date of format mm/dd/yyyy
also, i.e. both formats are needed. How to achieve this?
According to the Spring documentation of DataBinder#registerCustomEditor, only one single registered custom editor per property path is supported.
This means (as you probably already know), that you won't be able to bind two custom editors to the same class. In simple words, you can't have:
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("dd-MM-yyyy"), true));
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("dd/mm/yyyy"), true));
However, you can register your own implementation of DateFormat
that would behave as you wish, relying on your two required SimpleDateFormat
s.
For example, consider this custom DateFormat
(below), which can parse Date
s that are either in the "dd-MM-yyyy"
or "mm/dd/yyyy"
format:
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;
}
}
Then, you'd simply have to bind Date.class
to a CustomDateEditor
constructed over an instance of MyDateFormat
, as follows:
binder.registerCustomEditor(Date.class, new CustomDateEditor(new MyDateFormat(), true));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With