AndroidGuy AndroidGuy - 1 month ago 12
Java Question

calculate number of weeks in a given year

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
,
2020
and
2026
actually have
53
weeks.

Is there any way that I can calculate this, or any functions that will help me out?

Answer

According to the wikipedia article on ISO week date format, You can calculate it using following code.

    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, 2015);
    cal.set(Calendar.MONTH, Calendar.DECEMBER);
    cal.set(Calendar.DAY_OF_MONTH, 31);

    int ordinalDay = cal.get(Calendar.DAY_OF_YEAR);
    int weekDay = cal.get(Calendar.DAY_OF_WEEK) - 1; // Sunday = 0
    int numberOfWeeks = (ordinalDay - weekDay + 10) / 7;
    System.out.println(numberOfWeeks);
Comments