PHP date() and 53 weeks

Let’s say you have a bunch of statistical data.  And all that data is date-related.  And let’s say want to display that data on a chart, a weekly average or something along those lines.  One of the ways for you to place the value into the proper week would be something like this:

$week = date('W', strtotime($stats_date));
$values[$week][] = $stats_value;

And if you did it this way, sooner or later, you’d notice that something is not quite working right at the edges of your chart.  With code as simple and straight-forward as this, you’d probably look for the problem elsewhere.  Maybe it’s your statistical data which is wrong, or the graph is not generated properly.  But the problem is here.

How many weeks do you think there are in a year?  A common knowledge says 52.  However, if you think for a moment about how the weeks are related to the year, you’ll realize that the first and last weeks don’t necessary start and end at the edge of the year.  If you play around with 1st of January and 31st of December across several years, you’ll notice that sometimes they fall into the 53rd week.  (As do a few more days, not just these two).

And here, the problem with the “W” date() format starts to emerge.   When scattering your data across a single year, you’d most often expect January to start with the first week of the year.  But it doesn’t. Sometimes the start of it falls into the 53rd week of the previous year.  And date(‘W’, $your_time) will happily return 53.  What will this do to your chart?  Two things are most likely.  The first week’s values would get reduced, and the last week’s values would get increased.  Or those values of the first week would altogether vanish from the graph.  That is unless you are careful.  Which I hope you’ll now be.

See comments to PHP date() manual for several solutions of this problem.

6 thoughts on “PHP date() and 53 weeks”


  1. Hey Leonid,

    Thanks for the writeup -- good to inform people of these things.

    However, if you’ve ever looked at a calendar with week numbers, you’d have noticed that they also display the 53rd week. For quite a long time now (eg look at dec. 2009).

    So, concluding, i must say that any one working even remotely seriously with dates should know this :-)


  2. This is not a problem with the date() function, but with the logic an unaware programmer might use.

    Just wanted to clear that up =) If not, some PHP haters (and look around, there are many) might start flaming even if there’s a reason for this.


  3. Thanks for this. (posted on my birthday too lol). I was working on a script that automatically processes orders every 2 weeks, and initially I wanted to use the date(‘W’) for this, like if an order is made in even numbered weeks, then they will only get processed in even numbered weeks. This script will fail since you mentioned it’s possible to get the value of 53. :-/ Time to come up with another way to do my script!

Leave a Comment