7

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.

Josh Buhler
  • 26,878
  • 9
  • 29
  • 45
user1411335
  • 3,139
  • 3
  • 18
  • 24

2 Answers2

8

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.

zw324
  • 26,764
  • 16
  • 85
  • 118
  • +1 Exactly right. Just one of the many reasons that Calendar is the most broken class in the JDK. (Use JodaTime!) – Bohemian Jul 02 '13 at 22:13
3

Leniency merely controls whether or not the calendar accepts out-of-range dates. If leniency is set, Java will do some math to adjust out-of-range dates (for example, 2013-12-32 becomes 2014-01-01). If leniency is not set, Java will not allow this, but it doesn't check for out-of-range data until you actually request some of the fields. From the Javadocs:

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.

To your question then:

How do I handle this?

You can set the calendar to the first of the month:

calendar.set(2013, Calendar.JANUARY, 1);

and then invoke

int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); 

and compare against your day value. If your day value is in range, then you can proceed.

jason
  • 236,483
  • 35
  • 423
  • 525