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.