Java DateFormat: most convenient & elegant way to validate input date against multiple patterns
I'm doing like that now:
......
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
try{
dateFormat.parse(criteria.getPeriodFrom());
dateFormat.parse(criteria.getPeriodTo());
}
catch{
errors.reject("开发者_StackOverflow社区Incorrect format");
}
......
But what if I need to validate against few acceptable patterns (ex. "dd.MM.yyyy", "ddMMyyyy" ....). And I don't want to do any copy&paste or iterate through collection of DateFormats :) Are there cool libraries for that?
Just put the loop outside the try/catch block:
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");
}
Unforunately neither the Java built-in libraries nor the normally-excellent Joda Time have anything like .NET's DateTime.TryParseExact
which lets you test whether a parse operation works, without the ugly exception :( Mind you, at least Joda Time's formatters are thread-safe and immutable.
EDIT: I may be wrong... apparently DateFormat.parse(String, ParsePosition)
just returns null on failure, so you could use:
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))
}
精彩评论