我现在就这样:
......
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
try{
dateFormat.parse(criteria.getPeriodFrom());
dateFormat.parse(criteria.getPeriodTo());
}
catch{
errors.reject("Incorrect format");
}
......
但是,如果我需要针对少数可接受的模式(例如“ dd.MM.yyyy”,“ ddMMyyyy” ….)进行验证怎么办?而且我不想通过DateFormats的集合进行任何复制粘贴或迭代:)是否有很棒的库?
最佳答案
只需将循环放在try / catch块之外:
boolean success = false;
for (DateFormat candidate : formats) {
try {
candidate.parse(criteria.getPeriodFrom());
candidate.parse(criteria.getPeriodTo());
success = true;
break;
}
catch (ParseException e) {
// Expected... move on
}
}
if (!success) {
errors.reject("Incorrect format");
}
不幸的是,无论是Java内置库还是通常出色的Joda Time,都没有.NET的DateTime.TryParseExact之类的东西,它可以让您测试解析操作是否正常工作,而不会带来难看的异常:(请注意,至少Joda Time的格式化程序是线程安全的并且一成不变.
编辑:我可能是错的…显然DateFormat.parse(String, ParsePosition)
失败时只是返回null,因此您可以使用:
for (DateFormat candidate : formats) {
if (isValid(candidate, criteria)) {
// whatever
}
}
...
private static boolean isValid(DateFormat format, Criteria criteria) {
return format.parse(criteria.getPeriodFrom(), new ParsePosition(0)) != null &&
format.parse(criteria.getPeriodTo(), new ParsePosition(0)) != null))
}