I would like to get the number of weeks in any given year. Even though 52
is accepted as a generalised worldwide answer, the calendars for 2015
,
This method calculates the number of weeks a ISO year using the Joda time library.
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
public static int weeksInYear(int year) {
return new DateTime(DateTimeZone.forID("America/Los_Angeles"))
.withWeekyear(year + 1)
.withWeekOfWeekyear(1)
.minusWeeks(1)
.getWeekOfWeekyear();
}
@Manjula Weerasinge answer actually introduce a bug for 2016. Here's a better solution.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DAY_OF_MONTH, 1);
GregorianCalendar gregorianCalendar = new GregorianCalendar();
int weekDay = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (gregorianCalendar.isLeapYear(year)){
if (weekDay == Calendar.THURSDAY || weekDay == Calendar.WEDNESDAY)
return 53;
else
return 52;
} else {
if (weekDay == Calendar.THURSDAY)
return 53;
else
return 52;
}
For ISO date format, we can calculate number of weeks as follows:
int getNoOfWeeks(int year) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.setMinimalDaysInFirstWeek(4);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
return cal.getActualMaximum(Calendar.WEEK_OF_YEAR);
}
So, for year = 2018, it will return 52, for 2019, it will also return 52, but for 2020 it will return 53 as ISO year has 52 or 53 weeks.