|
Suck: GregorianCalendar
// Create a calendar object.
GregorianCalendar cal = new GregorianCalendar();
// Clear out all the fields.
cal.clear();
// Set the week number.
cal.set( Calendar.WEEK_OF_YEAR, 1 );
// Set the year.
cal.set( Calendar.YEAR, 2005 );
// Foolishly attempt to read back what I just set:
assert( cal.get( Calendar.YEAR ) == 2005 );
// fails!
Of course, any week number greater than 1 works (even past 53, assuming cal.setLenient(true)), leading to New Year's Day debugging fun.
Update: Mikko Wilkman writes:
I just have to comment on that after having a bit of a fight with the Calendar classes myself yesterday.. This might be already old news to you, but here goes:
The GregorianCalendar uses the default Locale to determine what week that week 1 actually is. At least on my machine GregorianCalendar says that by default the first week is the week starting on Sunday, and the week has to have at least one day in it. Unfortunately, that makes Sunday 26th Dec 2004 -> Saturday 1st Jan 2005 the first week of 2005, and it actually works as it is supposed to, and the GregorianCalendar's internal time is set to the first date of that week, being 26th Dec :) There is a method in GregorianCalendar, getISOYear() for fetching the year related to the week number, which would return 2005 in your case as well, but unfortunately the method is package private. I hope it becomes public soon :)
Now when I need to use week numbers with GregorianCalendar, I always do setFirstDayOfWeek(Calendar.MONDAY) and setMinimalDaysInFirstWeek(4) (that's our standard week here in Finland) to make sure the class does what I really need it to do.
Thanks, Mikko. It wasn't old news to me. For what it's worth, this is the gross code I ended up using to work-around the issue:
public static GregorianCalendar calFrom(int year, int weekOfYear) {
GregorianCalendar cal = new GregorianCalendar();
cal.clear();
cal.set(Calendar.YEAR, year);
while(cal.get(Calendar.WEEK_OF_YEAR) != weekOfYear)
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
return cal;
}
Monday, January 03, 2005
12:00 AM
|