javadatejava.util.calendar

Checking if the date is valid using Calendar


I want to use calendars method to set year date and month but want some kind of indication if the date is invalid e.g.

calendar.set(2013,Calendar.JANUARY , 23) //is a valid date
calendar.set(2013,Calendar.JANUARY , 33) //is not

I set calendar.setLenient(false) and expected that setting the value to January 33rd would throw an exception, but it did not.


Solution

  • It seems the check is done lazily:

    A non-lenient GregorianCalendar throws an exception upon calculating its time or calendar field values if any out-of-range field value has been set.

    So this will throw you an exception:

    Calendar c = new GregorianCalendar();
    c.setLenient(false);
    c.set(2013, Calendar.JANUARY, 33);
    c.getTime();
    

    But not without the getTime.