davioooh davioooh - 4 months ago 21
Java Question

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
CustomDateEditor
s in my controller?

Answer

If at a time you receive only one format of date, then you could simply create one instance of DateFormat based on format

for example

Decide the format based on the input

DateFormat df = null;
if(recievedDate.indexOf("//")!=-1){
    df = new SimpleDateFormat("dd/MM/yyyy")
}else{
    df = new SimpleDateFormat("yyyyMMddhhmmss")
}