What are the best ways to validate the channel date to be valid by format?


Started working with WEB UI recently. And encountered a problem of date string parsing/validation. "dd-mm-yyyy" Some approaches I found are:

  1. Matching - not complete validation, not flexible.

    (19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])

  2. There was a post where guy suggest to preinitialize Set with possible date string - fast, valid, but also not flexible and memory consuming

Is there something easier, maybe available in public libs ?

Please don't suggest SimpleDateFormat :)

UPDATE for java 8 correct answer is https://stackoverflow.com/a/43076001/1479668

If you are using java 8 then DateTimeFormatter is what you are looking for. The link to javadoc also contains sample code and a number of predefined formats. Besides you can also define your own.

Here is some code, an example from the same link:

LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
String text = date.format(formatter);
LocalDate parsedDate = LocalDate.parse(text, formatter);

Also, this How to parse/format dates with LocalDateTime? (Java 8) question has got some fantastic answers.

EDIT: Thanks Basil Bourque for the updates about ThreeTen-Backport project in case one needs to use almost the same features as provided by java 8 in some older versions of java.