gpt4 book ai didi

php - 跨年 DatePeriod 宽度 DateInterval P7D 不计新年周

转载 作者:可可西里 更新时间:2023-11-01 00:43:51 24 4
gpt4 key购买 nike

我正在尝试像这样使用 PHP DatePeriod 来创建一个年周数组:

$from = new DateTime('2014-09-16');
$to = new DateTime('2015-02-25');

$interval = new DateInterval('P7D'); // 7Days => 1 Week
$daterange = new DatePeriod($from, $interval, $to);

$yearweeks = array();
foreach($daterange as $date) {
$yearweeks[$date->format('YW')] = 'W' . $date->format('W-Y');
}

结果很奇怪!新年的第一周不见了。我有前一年的第一周而不是这样:

Array
(
...
[201451] => W51-2014
[201452] => W52-2014
[201401] => W01-2014 // WTF ? /!\ [201501] => W01-2015 expected ! /!\
[201502] => W02-2015
[201503] => W03-2015
...
)

是否有避免此类错误的技巧?

最佳答案

您需要使用 ISO 年份,格式为 'o':

$yearweeks[$date->format('oW')] = 'W' . $date->format('W-o');

来自PHP date docs :

o

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)

Examples: 1999 or 2003

关于php - 跨年 DatePeriod 宽度 DateInterval P7D 不计新年周,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25871007/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com