我有這個 Java 類:
package TestPackage;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class TestSimpleDateFormat {
private static final String DATE_FORMAT = "dd/MM/yyyy";
private String dob;
public boolean isValidDate(String day, String month, String year) {
boolean isValid;
DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
formatter.setLenient(false);
try {
formatter.parse(extractDateOfBirthFrom(day, month, year));
isValid = true;
}
catch (ParseException e){
isValid = false;
}
return isValid;
}
private String extractDateOfBirthFrom(String day, String month, String year) {
String dob = day.concat("/").concat(month).concat("/").concat(year);
return dob;
}
}
當我在主程式中運行以下命令時,我得到了true日期驗證的回應值:
TestSimpleDateFormat testSimpleDate = new TestSimpleDateFormat();
System.out.println("Is date valid: " testSimpleDate.isValidDate("01", "01", "81"));
由于我只通過了 yy 而不是 yyyy 一年,我預計驗證會失敗。是否可以yyyy僅強制檢查?
uj5u.com熱心網友回復:
問題是 yy 是正確的,因為 DateFormat 將作為有效年份,那么您需要添加其他驗證,也許使用正則運算式來驗證日期的格式。
也許你可以試試:
try {
String dob = main.extractDateOfBirthFrom(day, month, year);
java.util.Date date = formatter.parse(dob);
isValid = true;
dob.matches("^([0-2][0-9]|(3)[0-1])(\\/)(((0)[0-9])|((1)[0-2]))(\\/)\\d{4}$") ? isValid = true : isValid = false;
}
catch (ParseException e){
isValid = false;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/383716.html
