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?
If at a time you receive only one format of date, then you could simply create one instance of
DateFormat
based on formatfor example
Decide the format based on the input
If you need it only at puntual cases, you can register the custom editor attached to a field in the form:
Inspired by Skipy
For others having the same question, if you are using spring 3 You can use the awesome @DateTimeFormat(pattern="dd-MM-yyyy") in the field of your model.
Just make sure to register a conversionService with your org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
You can have as much as you want of @DateTimeFormat in the same bean.
How about this. the above can go out of whack pretty soon.
This could also be referenced through Spring Converters via a CustomDateEditor implementation for form-data binding.
Not a great idea to have lenient date formatters when dealing with multiple locales. A date like 10/11/2013 will get parsed correctly with both dd/MM/YYYY and MM/dd/YYYY