SimpleDateFormat giving wrong date instead of error

Solution 1:

Use DateFormat.setLenient(false) to tell the DateFormat/SimpleDateFormat that you want it to be strict.

Solution 2:

Set Lenient will work for most cases but if you wanna check the exact string pattern then this might help,

    String s = "03/6/1988";
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    try {
        sdf.setLenient(false);
        Date d = sdf.parse(s);
        String s1 = sdf.format(d);
        if (s1.equals(s))
            System.out.println("Valid");
        else
            System.out.println("Invalid");
    } catch (ParseException ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace();
    }

If you give the input as "03/06/1988" then you'll get valid result.

Solution 3:

java.time

I should like to contribute the modern answer. When this question was asked in 2011, it was reasonable to use SimpleDateFormat and Date. It isn’t anymore. Those classes were always poorly designed and were replaced by java.time, the modern Java date and time API, in 2014, so are now long outdated.

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu")
            .withResolverStyle(ResolverStyle.STRICT);

    String dateString = "13-13-2007";
    LocalDate date = LocalDate.parse(dateString, dateFormatter);

This code gives the exception you had expected (and had good reason to expect):

Exception in thread "main" java.time.format.DateTimeParseException: Text '13-13-2007' could not be parsed: Invalid value for MonthOfYear (valid values 1 - 12): 13

Please also notice and enjoy the precise and informative exception message.

DateTimeFormatter has three so-called resolver styles, strict, smart and lenient. Smart is the default, and you will rarely need anything else. Use strict if you want to be sure to catch all invalid dates under all circumstances.

Links

  • Oracle tutorial: Date Time explaining how to use java.time.
  • uuuu versus yyyy in DateTimeFormatter formatting pattern codes in Java?