【问题标题】:Date validation for Java 8 Time API in SpringSpring 中 Java 8 Time API 的日期验证
【发布时间】:2016-12-02 20:48:55
【问题描述】:

我们都知道initBinder 方法内部的控制器中日期验证的经典示例:

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

但是,我们需要将DateFormat 替换为DateTimeFormatter,来支持新的Java 8 Time API 的替代方案是什么? Spring 框架为此提供了哪些工具?

谢谢。

【问题讨论】:

    标签: java spring java-8 date-format


    【解决方案1】:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-27
      • 2017-07-29
      • 1970-01-01
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多