ArthurV
ArthurV

Reputation: 123

Date format exception is not caught

public OrderDate(String date) throws IllegalDateFormatException {   
  SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yy");
  try {
    dateFormat.parse(date);
    this.date = date;
  } catch (ParseException e) {
    throw new IllegalDateFormatException("Date must have the following format: dd/mm/yy");
  }
}

If I use for example 32/05/12 - it doesn't throw an exception.

I also tried: Date givenDate = dateFormat.parse(date);

Need clarification.

Update:

public OrderDate(String date) throws IllegalDateFormatException
{   
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yy");
    try 
    {
        dateFormat.setLenient(false);
        dateFormat.parse(date);
        this.date = date;
    }
    catch(ParseException e) 
    {
        throw new IllegalDateFormatException("Date must have the following"
                                                     + " format: dd/mm/yy");
    }
}

It catches the exception, if the date is 32/06/12! At the same time, there is no catch, if the date is 31/06/12. But there are 30 days in June!

Upvotes: 0

Views: 113

Answers (1)

Masudul
Masudul

Reputation: 21961

By default, setLenient of SimpleDateFormat is true. So, whenever you parse 32/05/12, it is automatically converted to 01/06/12. That why no exception is throws. If you need strict parsing than use setLenient(false), it will throw Exception at above case. Look at the docs.

Specify whether or not date/time parsing is to be lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format. With strict parsing, inputs must match this object's format.

Upvotes: 1

Related Questions