在我的java程序中,java变量String inputDate
接受输入表单用户。我想强制用户以(dd / MM / yyyy)格式输入日期,因为我的其他模块仅依赖于该格式。这是我到目前为止所尝试的:
public class InputQuery {
private static String FLIGHT_DATE;
public String getFLIGHT_DATE() {
return FLIGHT_DATE;
}
public void setFLIGHT_DATE() {
boolean invalid = true;
Scanner sc = null;
while(invalid){
System.out.println("Enter FLIGHT_DATE(dd/MM/yyy) :");
sc = new Scanner(System.in);
FLIGHT_DATE = sc.nextLine();
if( (invalid = isValidDate(FLIGHT_DATE)) ) {
System.out.println("For Feb 21,2016 enter 21/02/2016");
}
}
sc.close();
}
private boolean isValidDate(String flight_DATE) {
SimpleDateFormat myDateFormat = new SimpleDateFormat("dd/MM/yyyy");
if( flightDate.parse(flight_DATE)){
System.out.println("accepted OK");
return true;
}
return false;
}
答案 0 :(得分:1)
使用myDateFormat.setLenient(false)
。
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setLenient(false);
try{
sdf.parse(incomingDateString);
// if you get here, the incomingDateString is valid
}catch(ParseException ex){
// if you get here, the incomingDateString is invalid
}
答案 1 :(得分:1)
这不起作用,试试这个
private boolean isValidDate(String flightDate) {
SimpleDateFormat myDateFormat = new SimpleDateFormat("dd/MM/yyyy");
myDateFormat.setLenient(false);
try {
myDateFormat.parse(flightDate);
} catch (ParseException e) {
return false;
}
System.out.println("accepted OK");
return true;
}
答案 2 :(得分:0)
据我了解,您要做的是确保输入的日期与格式相符。
parse(String)
方法不返回布尔值,它永远不会返回null
。如果成功,则返回日期;如果它不成功,它会抛出异常。这样做的方法是:
private boolean isValidDate(String flight_DATE) {
SimpleDateFormat myDateFormat = new SimpleDateFormat("dd/MM/yyyy");
try {
myDateFormat.parse(flight_DATE);
return true;
} catch (ParseException ex) {
// You may want to print the exception here, or do something else with it
return false;
}
}
答案 3 :(得分:0)
您可以使用正则表达式检查给定输入是否格式化尝试:
public class DateValidator {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String flightDate = null;
boolean isDateValid = false;
while(!isDateValid){
System.out.print("Enter FLIGHT_DATE(dd/MM/yyy) :");
flightDate = scanner.nextLine().trim();
isDateValid = isDateValid(flightDate);
if(!isDateValid){
System.out.println("Wrong Format.");
}
}
System.out.println("continue.");
}
public static boolean isDateValid(String flightDate){
String regex = "^\\d{2}/\\d{2}/\\d{4}$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(flightDate);
return matcher.find();
}
}