Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 849
AndroidGuy Avatar asked Jan 04 '12 08:01

AndroidGuy


People also ask

How do you calculate the number of weeks?

To calculate the number of weeks between two dates, start by counting the number of days between the start and end date. Then, divide that number by 7 days per week.

How do I calculate weeks in a year in Excel?

Explanation. The WEEKNUM function takes a date and returns a week number (1-54) that corresponds to the week of year. The WEEKNUM function starts counting with the week that contains January 1.

How do I calculate the number of weeks in Excel?

To find out how many weeks there are between two dates, you can use the DATEDIF function with "D" unit to return the difference in days, and then divide the result by 7. Where A2 is the start date and B2 is the end date of the period you are calculating.

Are there 50 or 52 weeks in a year?

There are 52 weeks in a year, and US companies are permitted to entitle staff to at least two weeks of paid holiday, sick leave, or personal days.


2 Answers

Quick one liner:

Integer weeksOfYear = Calendar.getInstance().getActualMaximum(Calendar.WEEK_OF_YEAR);
like image 131
Samuel Avatar answered Oct 13 '22 17:10

Samuel


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

like image 37
Manjula Avatar answered Oct 13 '22 19:10

Manjula