Skip to content
Advertisement

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?

Advertisement

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);

Update:

Seems the answer from @Samuel https://stackoverflow.com/a/40174287/201986 is better and free from the bug mentioned by Luca

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement