5

I want my controllers to parse dates in RequestParams and PathVariables according to a standard format.

Is it possible to set an application-wide @DateTimeFormat without annotating every @RequestParam individually?

Puneet Pandey
  • 960
  • 2
  • 14
  • 28
Can
  • 377
  • 2
  • 10

2 Answers2

2

You can do it at the controller level. Add @initBinder in your controller and it will format the date according to the given formatter.

@InitBinder
public void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setLenient(false);

    // true passed to CustomDateEditor constructor means convert empty String to null
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
Deendayal Garg
  • 5,030
  • 2
  • 19
  • 33
  • 1
    Not part of the original question but, is there a way to override this for individual request params? It seems that DateTimeFormat gets ignored when I use InitBinder. – Can May 05 '16 at 11:26
  • I do not see a way to do that. There might be a way but i am not aware of that. – Deendayal Garg May 05 '16 at 12:45
1

It might be possible by Spring AOP but how would you tell your code if you have different keys for date in request. but check following link for more derails:

Spring AOP Advice on Annotated Controllers

Community
  • 1
  • 1
sacgro
  • 459
  • 2
  • 5