开发者

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

开发者 https://www.devze.com 2023-04-09 07:59 出处:网络
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 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 althoug开发者_高级运维h 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).


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

0

精彩评论

暂无评论...
验证码 换一张
取 消