0

I know that a DateTimeFormat annotation can be defined on Date properties of a Model class in Spring but is there any way of defining a default dateTimeFormat annotation for all Dates in Spring Model classes?

@DateTimeFormat(pattern = "MM/dd/YYYY")
private Date deliveryDate;

It will save me from annotating each date field. It will also make it easy for me to change the application wide date format later on.

Fawad Shah
  • 1,680
  • 4
  • 15
  • 21
  • 1
    You can create a custom annotation that helps to parse date to your default format. However, you must add your custom annotation on Date properties at least – David Pham Nov 17 '16 at 03:59

2 Answers2

3

As kuhajeyan mentioned, you can use binder, but not on a controller, rather on controller advice, that will apply it globally:

@ControllerAdvice
public class GlobalDateBinder {

 /* Initialize a global InitBinder for dates*/

 @InitBinder
 public void binder(WebDataBinder binder) {
  // here you can use kuhajeyan's code
 }
}
Master Slave
  • 27,771
  • 4
  • 57
  • 55
1

in your controller

@InitBinder
protected void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/YYYY");
    binder.registerCustomEditor(Date.class, new CustomDateEditor(
            dateFormat, false));
}
kuhajeyan
  • 10,727
  • 10
  • 46
  • 71