javadateformaterror-checking

Java Validating Date entry


I want to know is there a way to check the Java Date format to makes sure that a user doesn't enter a date like 56-13-2013 where the format is dd-MM-yyyy. Currently when I enter a date with 13 months it will carry over to add one year and then will display 1 month. E.g. 16-16-2013 will give me 16-04-2014.


Solution

  • Use setLenient to validate the input Date String

    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    format.setLenient(false);
    Date date = format.parse(myDateString);