Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date binder of multiple formats in java

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?

like image 959
user3925230 Avatar asked Aug 09 '14 14:08

user3925230


1 Answers

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 SimpleDateFormats.

For example, consider this custom DateFormat (below), which can parse Dates 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));
like image 61
ccjmne Avatar answered Oct 05 '22 18:10

ccjmne