Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 784
jumps4fun Avatar asked Nov 28 '22 11:11

jumps4fun


2 Answers

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...

like image 160
ppeterka Avatar answered Nov 29 '22 23:11

ppeterka


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

The mistake is your assumption that Calendar.get(Calendar.DAY_OF_WEEK) is localized. It isn't. The mapping between day-of-week and number is fixed; use Calendar.getFirstDayOfWeek() to determine the human understanding of "first day of the week" if you need to; I'd be surprised if you really wanted to show a user "2" anyway... surely you'd want to show them the name of the day of the week.

Any calculations involving the start of the week should use getFirstDayOfWeek though.

like image 30
Jon Skeet Avatar answered Nov 30 '22 01:11

Jon Skeet