Question

I want to calculate the monday of a specific week number of a year. This is how I do it:

final GregorianCalendar calendar = new GregorianCalendar(Locale.GERMANY);
calendar.clear();
calendar.set(Calendar.YEAR, 2012); // set to 2012
calendar.set(Calendar.WEEK_OF_YEAR, 20); // set to week number 20
calendar.setTimeZone(TimeZone.getTimeZone("Europe/Berlin")); // set time zone

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yy"); // german format
System.out.println(sdf.format(calendar.getTime())); // return date

This has to return the 14th of May 2012 (14.05.12 in german format), but it returns the 16th of May 2012, but this is wrong.

So for 2012 its +2, 2011 is correct and 2010 is -1.

Why does the GregorianCalendar calculate the wrong date?

Thanks in advance and greets from germany.

Was it helpful?

Solution

Try setting the DAY_OF_WEEK, too:

final GregorianCalendar calendar = new GregorianCalendar(Locale.GERMANY);
calendar.clear();
calendar.set(Calendar.YEAR, 2012); // set to 2012
calendar.set(Calendar.WEEK_OF_YEAR, 20); // set to week number 20
calendar.set( Calendar.DAY_OF_WEEK, Calendar.MONDAY ); //set day to monday
calendar.setTimeZone(TimeZone.getTimeZone("Europe/Berlin")); // set time zone

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yy"); // german format
System.out.println(sdf.format(calendar.getTime())); // return date

Returns 14.05.12, 16.05.11 and 17.05.10 for me.

Edit:

So for 2012 its +2, 2011 is correct and 2010 is -1.

If I understand that correctly, you get 16.05.10, 16.05.11 and 16.05.12, right? That indicates that part of the calendar is reused. Did you, by any chance, test in a row starting with 2011? If so, changing the year only without any clear() etc. would keep the previously calculated date.

OTHER TIPS

It will depend on what getFirstDayOfWeek() returns and also what day the 1st of January falls on.

From Javadocs:

Values calculated for the WEEK_OF_YEAR field range from 1 to 53. Week 1 for a year is the earliest seven day period starting on getFirstDayOfWeek() that contains at least getMinimalDaysInFirstWeek() days from that year. It thus depends on the values of getMinimalDaysInFirstWeek(), getFirstDayOfWeek(), and the day of the week of January 1. Weeks between week 1 of one year and week 1 of the following year are numbered sequentially from 2 to 52 or 53 (as needed).

For example, January 1, 1998 was a Thursday. If getFirstDayOfWeek() is MONDAY and getMinimalDaysInFirstWeek() is 4 (these are the values reflecting ISO 8601 and many national standards), then week 1 of 1998 starts on December 29, 1997, and ends on January 4, 1998. If, however, getFirstDayOfWeek() is SUNDAY, then week 1 of 1998 starts on January 4, 1998, and ends on January 10, 1998; the first three days of 1998 then are part of week 53 of 1997.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top