Why does my GregorianCalendar object return the wrong day of week?

jumps4fun picture jumps4fun · Oct 2, 2013 · Viewed 11.9k times · Source

My issue is seemingly extremely simple. I make a calendar graphic user interface, from a GregorianCalendar object, and uses it's methods to calculate the correct number of days in the different months, and the different date's corresponding weekdays.

But the weekdays are consistentyl one day off. The Calendar claims that the 1st of July 2013 is a '2', which in my part of the world means tuesday. It should have been a '1' for Monday. "Easy!" i think, and put in the line: c.setFirstDayOfWeek(Calendar.MONDAY); But no reaction is given.

So I search stackoverflow for an answer, but everyone with my problem seem to have forgotten that January is 0, and not 1. I haven't. So now I am stuck.

As a simplifyed code, I have made a very short code piece, with it's corresponding output:

    GregorianCalendar c = new GregorianCalendar();
    c.setFirstDayOfWeek(Calendar.MONDAY);
    c.set(Calendar.MONTH, 6);
    c.set(Calendar.DAY_OF_MONTH, 1);
    c.set(Calendar.YEAR, 2013);

    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-YYYY");
    System.out.println(sdf.format(c.getTime()));
    System.out.println(c.get(Calendar.DAY_OF_WEEK));

and the output is:

01-07-2013

2

I refuse to put in a "-1" in my code, to wrongly correct the symptoms of what is obviously a mistake. Help is appreciated.

Answer

ppeterka picture ppeterka · Oct 2, 2013

Yes, date handling in Java is problematic...

  • Months start from 0 (JANUARY)
  • days of week start from SUNDAY being 1, SATURDAY being seven (Ideone fiddle)
  • c.setFirstDayOfWeek(Calendar.MONDAY); is a bit different than what the name suggests

    The first week of a month or year is defined as the earliest seven day period beginning on getFirstDayOfWeek() and containing at least getMinimalDaysInFirstWeek() days of that month or year

You can get out of troubles by always using the constants defined in the Calendar class, and not even trying to deduce any meaning from the numerical representations of those constants, or the results returned by the Calendar.get(int) method...