I'm trying to find an elegant way to find out if the format of a date satisfies at least one of a list of given formats. Concrete I have to validate a date against these 3 formats: YYYY, YYYY-MM and YYYY-MM-dd.
I tried with an example found in another thread, but it doesn't work:
private boolean checkDateFormat( String dateString )
{
String[] possibleDateFormats = new String[] { "yyyy", "yyyy-MM", "yyyy-MM-dd" };
boolean isValid = false;
for ( String possibleDateFormat : possibleDateFormats )
{
try
{
SimpleDateFormat simpleDateFormant = new SimpleDateFormat( possibleDateFormat );
simpleDateFormant.setLenient( false );
simpleDateFormant.parse( dateString.trim() );
isValid = true;
}
catch ( ParseException pe )
{
}
}
return isValid;
}
Another way is to use regex, but it will be quite complicated to cover all the possibilities.
Still another way is to parse the string and separately check the year, month and day. Something like this:
String[] parts = dateString.split("-");
boolean y = validateY(parts[0]);
boolean m = parts.length>1 ? validateM(parts[1]) : true;
boolean d = parts.length>2 ? validateD(parts[2]) : true;
return y && m && d;
But I find it not so "elegant".
Other ideas?
EXAMPLES (why code 1 doesn't work):
String[] possibleDates = new String[] { "999", "1001", "2001", "1", "123-3", "1234-13", "2015-12-31", "2015-13-31", "2015-12-32", "1-1-1" };
for (String date : possibleDates)
{
System.out.println(date + " : " + checkDateFormat(date));
}
OUTPUT(with and without break):
999 : true
1001 : true
2001 : true
1 : true
123-3 : true
1234-13 : true <- 13 months??
2015-12-31 : true
2015-13-31 : true <- 13 months??
2015-12-32 : true <- 32 days??
1-1-1 : true
EXAMPLE with Kartic code:
String[] possibleDateFormats = new String[] { "yyyy", "yyyy-MM", "yyyy-MM-dd" };
String[] possibleDates = new String[] { "999", "1001", "2001", "1", "123-3", "1234-13", "2015-12-31", "2015-13-31", "2015-12-32", "1-1-1", "0-00-0" };
boolean isDate = false;
for ( String date : possibleDates )
{
for ( String strDate : possibleDateFormats )
{
isDate = isValidDate( date, strDate );
if ( isDate )
{
break;
}
}
System.out.println(date + " :- " + isDate);
}
The output is the same...