当周跨越两年时,从 PHP date() 获取一年中的年份和周

发布于 2024-12-07 10:15:45 字数 539 浏览 0 评论 0原文

我在使用 PHP 的 date() 函数时遇到了一个有趣的问题。还没有找到关于这个问题的讨论或使用谷歌,但也许其他人以前遇到过同样的问题?

我正在尝试获取给定时间戳的年份和年份。这是我正在使用的代码:

date("Y-\WW");

截至今天,它正确输出:2011-W39

问题是在提供时间戳时,如果有问题的时间戳是 2011 年 1 月 3 日(实际上是“2010 年第 52 周”的一部分)。PHP 正确返回 W52,但它也返回 2011 年作为年份,而不是 2010。

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

输出: 2011-W52

有关如何解决此问题的任何想法吗?我应该注意,尽管在这种情况下很容易比较输出的 strtotime()大于当前的 time() 并进行调整,但我需要一个也适用于前几年的解决方案(例如,如果 2010 年 1 月 3 日发生了同样的事情)。

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).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌梦深 2024-12-14 10:15:45

天哪,显然我没有足够仔细地重新阅读文档,在 PHP 5.1.0 中添加了字母 o

来自 日期()

ISO-8601 年份编号。它与 Y 具有相同的值,但如果 ISO 周数 (W) 属于上一年或下一年,则使用该年。 (PHP 5.1.0 中添加)

所以我的代码应该是 date("o-\WW");

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文