Week numbers in Java

To do week number calculations in Java, you need configure a GregorianCalendar instance.

import java.util.GregorianCalendar; GregorianCalendar calendar = new GregorianCalendar(); calendar.setFirstDayOfWeek(GregorianCalendar.MONDAY); calendar.setMinimalDaysInFirstWeek(4); calendar.setTime(date);

The variable date is a java.util.Date instance.

How to get the week number from a date

To get the ISO week number (1-53), configure a GregorianCalendar instance as shown above and call calendar.get(GregorianCalendar.WEEK_OF_YEAR).

To get the corresponding four-digit year (e.g. 2013), use calendar.getWeekYear().

Read more about GregorianCalendar in the Java documentation.

How to get the date from a week number

To get the date from a year and week number, configure a GregorianCalendar instance as shown above and call calendar.setWeekDate(year, week, GregorianCalendar.MONDAY).

The variable year is a four-digit year, and week is an ISO week number (1-53).

Then call calendar.getTime() to get a java.util.Date instance.

Read more about setWeekDate() in the Java documentation.

How to get the number of weeks in a year

To get the number of ISO weeks (i.e. the number of the last week) in a year, configure a GregorianCalendar instance as shown above with date referencing a some date in the year in question, and then call calendar.getActualMaximum(GregorianCalendar.WEEK_OF_YEAR).

If the variable year is an integer four-digit year, set the reference date to e.g. June 1, i.e. date = Date(year, 6, 1).

Read more about getActualMaximum() in the Java documentation.