user3356383
user3356383

Reputation: 13

PHP strtotime +1 week error

I have a problem with strtotime and the following code (I want all calendar weaks in the given time range)

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

the var_dump produces the following output

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',
)

The Problem is entry number 52 with '2014-01', it should be '2015-01'. With the timerange 2015-01-01 till 2016-03-01 the result is ok. Is this a bug in strtotime function? I'm using PHP version 5.5.10

Thanks for your help.

Upvotes: 0

Views: 515

Answers (2)

John Conde
John Conde

Reputation: 219864

This has to do with ISO week numbers. Also, strtotime() is a bad way to do date math and PHP recommends against it (thanks to leap years and daylight savings). Use the DateTime() classes to do this with accuracy:

$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

Upvotes: 2

Kevin
Kevin

Reputation: 41875

Change this line and use the o iso year:

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

Upvotes: 3

Related Questions