7

I am using following pattern and date

Date : 13-13-2007

Pattern : dd-MM-yyyy

Output: Sun Jan 13 00:00:00 IST 2008 Or 2008-01-13 00:00:00.0

I was expecting exception here. What can i do to generate exception when given date is inproper.

Andrzej Doyle
  • 97,637
  • 30
  • 185
  • 225
Amit Kumar Gupta
  • 6,271
  • 11
  • 54
  • 77

3 Answers3

14

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

Joachim Sauer
  • 278,207
  • 54
  • 523
  • 586
  • After doing changes, you mentioned, it is giving parsing err in date:"13-10-2007 16:52:12.014789", pattern:"dd-MM-yyyy HH:mm:ss.SSSSSS". – Amit Kumar Gupta May 17 '11 at 11:55
  • I found the answer. Java supports 3 digit in ms field means dd-MM-yyyy HH:mm:ss.SSS is supportable – Amit Kumar Gupta May 17 '11 at 12:36
  • **Update:** This Answer is now obsolete as of the adoption of JSR 310. For the modern solution using *java.time* classes, see [the Answer](https://stackoverflow.com/a/55021417/642706) by Ole V.V. – Basil Bourque Mar 06 '19 at 16:47
3

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.

Ajeesh
  • 1,392
  • 2
  • 16
  • 28
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");

    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

Ole V.V.
  • 65,573
  • 11
  • 96
  • 117