簡體   English   中英

驗證提供給SimpleDateFormat新實例的輸入

[英]Validate input given to SimpleDateFormat new instance

有什么方法(正則表達式或其他方法)來驗證輸入到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;
    }
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM