PHP script: How many weeks is there in a year?

Icon ask Sir Apfelot

Icon ask Sir ApfelotThe 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:

  • Date Time
  • setISODate
  • Date () function
  • Incidentally, the triple equals === in PHP means that not only the comparison of the values ​​of the variables must be the same, but also the type of the variable (integer, string etc.) must be the same.

Which years have 52 or 53 calendar weeks?

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

-
 

 

Effectively for free: iPhone 13 Mini and iPhone 13 deals with top conditions at Otelo - Advertisement

Leave a Comment

Your e-mail address will not be published. Required fields are marked with * .