有什么方法(正则表达式或其他方法)来验证输入到SimpleDateFormat的新实例的输入?

例如:

 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

最佳答案

我认为您可以进行虚拟解析以检查格式是否有效

boolean validate(String input){
    try {
        new SimpleDateFormat(input).format(new Date());
        return true;
    }
    catch(Exception e) {
        return false;
    }
}

10-04 21:33
查看更多