Search code examples
javacalendargregorian-calendar

Unable to set GregorianCalendar Month and Date


Im trying to set the month and date of a Gregorian Calendar:

GregorianCalendar startCalendar = new GregorianCalendar();

startCalendar.set(GregorianCalendar.MONTH, 3);
System.out.println(startCalendar.MONTH);
startCalendar.set(GregorianCalendar.DATE, 9);
System.out.println(startCalendar.DATE);

The output is:

2
5

It doesn't seem to matter which numbers i use (ie. if i replace the 3 and 9), it always has the same output


Solution

  • References:

    MONTH and DATE are field numbers and aren't the actual value of the fields. You should use get() method to get the number set.

    GregorianCalendar startCalendar = new GregorianCalendar();
    
    startCalendar.set(GregorianCalendar.MONTH, 3);
    System.out.println(startCalendar.get(GregorianCalendar.MONTH));
    startCalendar.set(GregorianCalendar.DATE, 9);
    System.out.println(startCalendar.get(GregorianCalendar.DATE));