Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting year and week of year from PHP date() when week spans two years

Tags:

date

php

I have run into an interesting issue using PHP's date() function. Haven't had any luck locating a discussion of this on SO or using Google, but maybe someone else has run into the same issue before?

I am trying to get the YEAR and the WEEK OF THE YEAR for a given timestamp. This is the code I am using:

date("Y-\WW");

Which as of today correctly outputs: 2011-W39.

The problem is when supplying a timestamp, if the timestamp in question is, for example, on January 3rd, 2011 (which was actually part of the "52nd week of 2010". PHP correctly returns W52, but it also returns 2011 as the year, instead of 2010.

date("Y-\WW", 1294016400);

Outputs: 2011-W52

Any idea on how to solve this problem? I should note that although in this case it would be easy to just compare that the strtotime() of the output is greater than the current time() and adjust, but I need a solution that will work for previous years as well (e.g. if the same thing happened for January 3rd 2010).

like image 418
Riley Dutton Avatar asked Sep 30 '11 13:09

Riley Dutton


1 Answers

Darn, apparently I didn't re-read the documentation closely enough, the letter o was added in PHP 5.1.0:

From the documentation for date():

ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0)

So my code should have been date("o-\WW");

like image 112
Riley Dutton Avatar answered Sep 22 '22 00:09

Riley Dutton