2

GregorianCalendar constructor have signature:

GregorianCalendar(int year, int month, int dayOfMonth)
GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second) 

What happen if I pass month or dayOfMonth out of constructor contract?

It is easy to check if month in 0-11 range. But it is impossible to check valid day (which should be 28/29/30/31?) without writing own Calendar implementation.

It should be nice if Java Platform checks user date input. I don't like to check if 2015-13-32 is valid ISO date in own code.

gavenkoa
  • 45,285
  • 19
  • 251
  • 303

1 Answers1

3

The constructor doesn't check, what you can do is to set the time after executing setLenient(false) which will make the Calendar to accept only valid values:

Calendar cal = Calendar.getInstance();
cal.setLenient(false);
cal.set(2016, Calendar.FEBRUARY, 30);
System.out.println(new SimpleDateFormat("dd/MM/yyyy").format(cal.getTime()));

This example will throw an exception because 02/30/2016 is not a valid date (the exception is thrown by cal.getTime()).

Mateus Viccari
  • 7,389
  • 14
  • 65
  • 101