tomaszsvd tomaszsvd - 29 days ago 18
Java Question

Date Validation, user input

I'm working on the application where user enters a start date. The end date is taken from the system and difference between those two dates is calculated. However I would like to restrict the user input to the date no earlier than 01/01/2016. The date before doesn't work in this example. The user date is a string input. Any suggestions on how to apply this constraint?

System.out.println("Enter date: DD/MM/YYYY");
String date = input.next();

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
dateFormat.setLenient(false);
try {
if (date.before("01/01/2016")){ // this doesent work (can't resolve method)
System.out.println("Please enter later date");
}
dateFormat.parse(date);


} catch (ParseException e) {
System.out.println("Invalid Date, Please Try Again" + e);
return true;
}

Answer

your date variable is a String, you have to parse it before the compare

System.out.println("Enter date: DD/MM/YYYY");
String date = "";

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
dateFormat.setLenient(false);
try {

  Date pasedDate = dateFormat.parse(date);
  Date startDate = dateFormat.parse("01/01/2016");
  if (pasedDate.before(startDate)) { 
    System.out.println("Please enter later date");
  }

} catch (ParseException e) {
  System.out.println("Invalid Date, Please Try Again" + e);
  return true;
}