Search code examples
javacalendardayofweekgregorian-calendarweekday

GregorianCalendar returns wrong DAY_OF_WEEK in Java


This code:

Calendar calendar;
calendar = GregorianCalendar.getInstance();
calendar.set(year, month, day);
week_day = calendar.get(Calendar.DAY_OF_WEEK);

returns wrong value.

For example

  • year=2013, month=3, day=31

returns the same value of

  • year=2013, month=4, day=1.

How I can do this correctly ?


Solution

  • In Java, months start from 0.

    Month 3 day 31 is April 31, that does not exist, then it will be shifted to May 1,

    Month 4 day 1 is May 1, the same day as above.