Chapter in this post:
The question actually sounds easy at first: How can I use a PHP script to calculate how many weeks a year has? You would think the problem could be solved by dividing the number of days in a year by seven, but that is unfortunately not the correct answer. The reason for this lies in the ISO-8601 specification, which says that December 28th is always the last week of the year.
There are several mutually equivalent and compatible descriptions of week 01:
- the week with the year's first Thursday in it (the formal ISO definition),
- the week with 4 January in it,
- the first week with the majority (four or more) of its days in the starting year, and
- the week starting with the Monday in the period 29 December - 4 January.
As a consequence, if 1 January is on a Monday, Tuesday, Wednesday or Thursday, it is in week 01. If 1 January is on a Friday, Saturday or Sunday, it is in week 52 or 53 of the previous year (there is no week 00). December 28th is always in the last week of its year.
The week number can be described by counting the Thursdays: week 12 contains the 12th Thursday of the year.
I have the corresponding PHP script that takes this specification into account and based on it checks whether a year has 52 or 53 weeks Stackoverflow found:
function getIsoWeeksInYear ($ year) {$ date = new DateTime; $ date-> setISODate ($ year, 53); return ($ date-> format ("W") === "53"? 53:52); } // Example: Get the number of weeks for the year 2008 $ year = 2008; echo "Number of weeks in the year". $ year. ":" .getIsoWeeksInYear ($ year). "Weeks";
I have to admit that I didn't fully understand it. If you want to take a closer look at how it works, you can use a few "echo" commands to find out what is happening in detail. I have linked the commands used here, in case you want to continue entering:
If one follows the ISO specification 8601, then for the years 2010 and 2020 a number of 53 weeks results, while for example 2008, 2009 and most other years only have 52 calendar weeks. You can create a longer list with the script above. ;-)
Jens has been running the blog since 2012. He appears as Sir Apfelot for his readers and helps them with problems of a technical nature. In his free time he drives electric unicycles, takes photos (preferably with his iPhone, of course), climbs around in the Hessian mountains or hikes with the family. His articles deal with Apple products, news from the world of drones or solutions for current bugs.