Spring中Java 8 Time API的日期验证 [英] Date validation for Java 8 Time API in Spring

查看:162
本文介绍了Spring中Java 8 Time API的日期验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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));
}

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

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?

谢谢。

推荐答案

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

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

这篇关于Spring中Java 8 Time API的日期验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆