Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC set global DateTimeFormat

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?

like image 901
Can Avatar asked Oct 19 '22 10:10

Can


1 Answers

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));
}
like image 198
Deendayal Garg Avatar answered Oct 21 '22 06:10

Deendayal Garg