Q:

Why GregorianCalendar returns 0 instead of MONTH?

I have a problem with creating dates. 
Calendar gc = new GregorianCalendar();
int leto = randBetween(2001, 2020);
gc.set(GregorianCalendar.YEAR, leto);
int dan= randBetween(1, gc.getActualMaximum(GregorianCalendar.DAY_OF_YEAR));
gc.set(GregorianCalendar.DAY_OF_YEAR, dan);
//   System.out.println(gc.get(GregorianCalendar.YEAR) + "-" +
//     gc.get(GregorianCalendar.MONTH) + "-" +
//     gc.get(GregorianCalendar.DAY_OF_MONTH));

public static int randBetween(int start, int end) {
  return start + (int)Math.round(Math.random() * (end - start));
}

I have a function for generating a date but in this function there are a lot of failures. I get many dates where the MONTH value is not set.
31,6,2004 1,7,2004
23,0,2013 24,0,2013
19,0,2008 20,0,2008 
31,9,2014 31,9,2014

But I don't know why this happens?

A:

This code is not ‘failing’, it is however not giving the expected result.
The dates that you are seeing are:
23,0,2013  -- 23rd of January, 2013.
31,6,2013  -- 31st of July, 2013.

That is, month is not 1-based, unlike day, it is 0-based.
Rest assured, this is fairly common mistake with the Java Date API, and probably the only person who thinks that is is logical is the person who came up with this API, and probably not even them anymore…

