2016-12-02 50 views
1

我们都知道一个日期验证的典型例子在initBinder方法内部控制器:在的Spring Java 8时API日期验证

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

但是,什么是支持新的Java 8时间替代API,我们需要将DateFormat更换为DateTimeFormatter? Spring Framework提供了哪些工具?

谢谢。

回答

3

binder.registerCustomEditor方法还不支持DateTimeFormatter,但在Spring 4中,您可以通过在pojo中使用@DateTimeFormat和Java 8 Date-Time(java.time)对象来实现此目的。

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 
} 

作进一步参考,请访问

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