Date validation for Java 8 Time API in Spring

2019-04-15 05:45发布

We all know the classic example of a date validation in the controller inside the initBinder method:

@InitBinder
public void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm");
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}

But what is the alternative to support the new Java 8 Time API, where we need to replace DateFormat to DateTimeFormatter? What tools Spring Framework provides for this?

Thanks.

1条回答
forever°为你锁心
2楼-- · 2019-04-15 06:35

The binder.registerCustomEditor method does not support DateTimeFormatter yet but in Spring 4 you can achieve this by using @DateTimeFormat with Java 8 Date-Time (java.time) objects in your pojo.

public class MyPojo {

  @DateTimeFormat(iso = ISO.DATE)
  private LocalDate localDate1;

  // you can use pattern as well
  @DateTimeFormat(pattern = "dd.MM.yyyy HH:mm")
  private LocalDate localDate2;

  // setters & getters
}

for further reference please visit

http://blog.codeleak.pl/2014/06/spring-4-datetimeformat-with-java-8.html

http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/format/annotation/DateTimeFormat.html

查看更多
登录 后发表回答