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("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:
Unforunately neither the Java built-in libraries nor the normally-excellent Joda Time have anything like .NET’s
DateTime.TryParseExactwhich 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: