PHP strtotime +1周错误

时间:2014-09-30 13:56:26

标签: php date strtotime week-number

我有strtotime和以下代码的问题(我希望在给定时间范围内所有日历弱点)

$all_dates = array();
$tempdate = '2014-01-01';
$enddate = '2015-03-01';

while (strtotime($tempdate) <= strtotime($enddate)) {
    $all_dates[] = date('Y-W', strtotime($tempdate));
    $tempdate = date('Y-m-d', strtotime($tempdate . '+1 week'));
}

var_dump($all_dates);

var_dump产生以下输出

array (
    0 => '2014-01',
    1 => '2014-02',
    2 => '2014-03',
    3 => '2014-04',
    4 => '2014-05',
    5 => '2014-06',
    6 => '2014-07',
    7 => '2014-08',
    8 => '2014-09',
    9 => '2014-10',
    10 => '2014-11',
    11 => '2014-12',
    12 => '2014-13',
    13 => '2014-14',
    14 => '2014-15',
    15 => '2014-16',
    16 => '2014-17',
    17 => '2014-18',
    18 => '2014-19',
    19 => '2014-20',
    20 => '2014-21',
    21 => '2014-22',
    22 => '2014-23',
    23 => '2014-24',
    24 => '2014-25',
    25 => '2014-26',
    26 => '2014-27',
    27 => '2014-28',
    28 => '2014-29',
    29 => '2014-30',
    30 => '2014-31',
    31 => '2014-32',
    32 => '2014-33',
    33 => '2014-34',
    34 => '2014-35',
    35 => '2014-36',
    36 => '2014-37',
    37 => '2014-38',
    38 => '2014-39',
    39 => '2014-40',
    40 => '2014-41',
    41 => '2014-42',
    42 => '2014-43',
    43 => '2014-44',
    44 => '2014-45',
    45 => '2014-46',
    46 => '2014-47',
    47 => '2014-48',
    48 => '2014-49',
    49 => '2014-50',
    50 => '2014-51',
    51 => '2014-52',
    52 => '2014-01',
    53 => '2015-02',
    54 => '2015-03',
    55 => '2015-04',
    56 => '2015-05',
    57 => '2015-06',
    58 => '2015-07',
    59 => '2015-08',
    60 => '2015-09',
)

问题是&#39; 2014-01&#39;的条目号52,它应该是&#39; 2015-01&#39;。随着时间范围2015-01-01至2016-03-01,结果还可以。这是strtotime功能中的错误吗? 我使用的是PHP 5.5.10版本

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

更改此行并使用o iso年:

$all_dates[] = date('o-W', strtotime($tempdate));
                 //  ^

答案 1 :(得分:2)

这与ISO周数有关。此外,strtotime()是一种做日期数学的坏方法,PHP推荐它(由于闰年和夏令时)。使用DateTime()类可以准确地执行此操作:

$startdate = new DateTime('2014-01-01');
$enddate   = new DateTime('2015-03-01');
$interval  = new DateInterval('P7D');
$period    = new DatePeriod($startdate , $interval, $enddate);

foreach($period as $date) {
    $all_dates[] = $date->format('o-W'); // o modifier for ISO year
}

var_dump($all_dates);

Demo