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?

2 Answers 2

1

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));
}
Sign up to request clarification or add additional context in comments.

2 Comments

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.
I do not see a way to do that. There might be a way but i am not aware of that.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.