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