简体   繁体   English

从PHP日期()获得一年中的一年和一周,当一周跨越两年

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

I have run into an interesting issue using PHP's date() function. 我使用PHP的date()函数遇到了一个有趣的问题。 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? 没有任何运气在SO上或使用谷歌进行讨论,但也许其他人之前遇到过同样的问题?

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 . 截至今天正确输出: 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. 问题在于提供时间戳,如果有问题的时间戳是,例如,2011年1月3日(实际上是“2010年第52周”的一部分.PHP正确返回W52,但它也返回2011年作为年份而不是2010年。

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

Outputs: 2011-W52 产出: 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 (eg if the same thing happened for January 3rd 2010). 我应该注意到,虽然在这种情况下很容易比较输出的strtotime()大于当前time()并进行调整,但我需要一个能够在前几年使用的解决方案(例如,如果同样的事情发生在2010年1月3日)。

Darn, apparently I didn't re-read the documentation closely enough, the letter o was added in PHP 5.1.0: Darn,显然我没有仔细阅读文档,在PHP 5.1.0中添加了字母o

From the documentation for date() : date()的文档:

ISO-8601 year number. ISO-8601年份编号。 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. 它具有与Y相同的值,除了如果ISO周数(W)属于上一年或下一年,则使用该年代。 (added in PHP 5.1.0) (在PHP 5.1.0中添加)

So my code should have been date("o-\\WW"); 所以我的代码应该是date("o-\\WW");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM