Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle different date formats in Spring MVC controller?

Is it possible to handle different date format in a Spring MVC controller?

I know that setting something like this

@InitBinder
protected void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    binder.registerCustomEditor(Date.class, new CustomDateEditor(
            dateFormat, false));
}

I can handle dd/MM/yyyy format, but what if i want to parse also dates in yyyyMMddhhmmss format? Should I add multiple CustomDateEditors in my controller?

like image 258
davioooh Avatar asked Dec 04 '22 03:12

davioooh


1 Answers

If you need it only at puntual cases, you can register the custom editor attached to a field in the form:

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", this.getLocale(context));
DateFormat dateTimeFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss SSS", this.getLocale(context));
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateTimeFormat, true));
binder.registerCustomEditor(Date.class, "name.of.input", new CustomDateEditor(dateTimeFormat, true));
like image 193
Thiamath Avatar answered Dec 28 '22 10:12

Thiamath