Reputation: 1861
Is there any way( regex or other way) to validate the input given to a new instance of SimpleDateFormat?
e.g. :
String input = getInputFromSomewhere();
if(validate(input)){
SimpleDateFormat sdf = new SimpleDateFormat(input);
//do my job with sdf
}
boolean validate(String input){
//what should be here????
}
String input = "yyyy-MM-dd" ; //or any other value which I can't control
String badFormatInput = "NOTHING" ;
System.out.println(validate(input)) ; //--> true
System.out.println(validate(badFormatInput)); //--> false
Upvotes: 0
Views: 89
Reputation: 17622
I think you can do dummy parsing to check whether the format is valid
boolean validate(String input){
try {
new SimpleDateFormat(input).format(new Date());
return true;
}
catch(Exception e) {
return false;
}
}
Upvotes: 3