3

我想验证格式的日期YYYY-MM-DD_hh:mm:ss

@Past //validates for a date that is present or past. But what are the formats it accepts

如果那不可能,我想使用@Pattern. 但是regex上述格式使用的是@Pattern什么?

4

2 回答 2

5

@PastDate仅支持Calendar但不支持字符串,因此没有日期格式的概念。

您可以创建一个自定义约束,例如@DateFormat确保给定字符串遵循给定日期格式,约束实现如下:

public class DateFormatValidatorForString
                           implements ConstraintValidator<DateFormat, String> {

    private String format;

    public void initialize(DateFormat constraintAnnotation) {
        format = constraintAnnotation.value();
    }

    public boolean isValid(
        String date,
        ConstraintValidatorContext constraintValidatorContext) {

        if ( date == null ) {
            return true;
        }

        DateFormat dateFormat = new SimpleDateFormat( format );
        dateFormat.setLenient( false );
        try {
            dateFormat.parse(date);
            return true;
        } 
        catch (ParseException e) {
            return false;
        }
    }
}

Note that the SimpleDateFormat instance must not be stored in an instance variable of the validator class as it is not thread-safe. Alternatively you could use the FastDateFormat class from the commons-lang project which safely can be accessed from several threads in parallel.

If you wanted to add support for Strings to @Past you could do so by implementing a validator implementing ConstraintValidator<Past, String> and registering using an XML constraint mapping. There would be no way to specify the expected format, though. Alternatively you could implement another custom constraint such as @PastWithFormat.

于 2013-07-09T06:57:23.680 回答
2

最好尝试使用 SimpleDateFormat 解析日期

boolean isValid(String date) {
   SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'_'HH:mm:ss");
   df.setLenient(false);
   try {
      df.parse(date);
   } catch (ParseException e) {
      return false;
   }
   return true;
}
于 2013-07-09T04:18:24.517 回答