Saif Idrees
Saif Idrees

Reputation: 31

How to validate any date format pattern itself in Java

I just could not find any way to check if the provided pattern is valid or not before validating any date.

For example

String datePattern = "blablabla";

How can we validate if it's a valid pattern to create an object SimpleDateFormat or any other dateFormat.

Thanks.

Upvotes: 2

Views: 7262

Answers (1)

Magnilex
Magnilex

Reputation: 11958

From the JavaDoc:

IllegalArgumentException - if the given pattern is invalid

In other words, catch the exception. If it's caught, it is an invalid pattern:

try {
    new SimpleDateFormat("invalid");
} catch (IllegalArgumentException e) {
    // invalid pattern
}

Upvotes: 3

Related Questions