Quirk with PHP DateTime ISO weeks

Jaxel

Well-known member
I have 3 values:
Code:
$timezone = new \DateTimeZone('America/New York');
$year = 2019
$week = 52

I then take these 3 values and run it through a script:
Code:
$nowTime = new \DateTime('now', $timezone);
$currTime = clone $nowTime;
$currTime->setISODate($year, $week, 1);
$currTime->setTime(0,0,0);

As you can see, I am setting the current time to be the beginning of Week 52 in 2019.

I am then trying to get information about the next week.
Code:
$nextTime = clone $currTime;
$nextTime->modify('+1 week');

$nextWeek = [
    'year' => $nextTime->format('Y'),
    'week' => $nextTime->format('W'),
];

This script has worked in almost every instance I have found...

Hopever, in Week 52 in 2019, instead of returning the next week as Week 1 in 2020, it returns the next week as Week 1 in 2019... which sends me backwards in time.

How do I fix this? This seems to happen in every year where there are 53 weeks in the year.
 
Your time zone definition doesn't work. You're missing the underscore in New_York. Doesn't affect the issue, which sounds similar to a bug reported 4 years ago in the comments: http://php.net/manual/en/datetime.modify.php#113549

PHP:
<?php
$timezone = new \DateTimeZone('America/New_York');
$year = 2019;
$week = 52;

$nowTime = new \DateTime('now', $timezone);
$currTime = clone $nowTime;
$currTime->setISODate($year, $week, 1);
$currTime->setTime(0, 0, 0);

echo $currTime->format('Y-m-d H:i:s') . "<br />";


$nextTime = clone $currTime;
$nextTime->modify('+1 week');

echo $nextTime->format('Y-m-d H:i:s');

2019-12-23 00:00:00
2019-12-30 00:00:00

So I would probably suggest not relying on the week number since everything else appears to work correctly.


Fillip
 
Also, according to Windows, there is no such thing as 53 weeks in a year, because any week that has the 1st of January in it is week 1:

1514652448210.webp

So the bug happens whenever you are adding 1 week to any day that means the resulting day is in week 1, but still in 2019. I would probably report this to PHP.


Fillip
 
ISO week numbers are weird and hard to logic about. The problem here is quite likely that you're using the "Y" date formatter, which is the calendar year, vs "o" which is ISO week numbering year. Note that some years can have 53 ISO week numbers.

I'm not positive, but I suspect the issue you're seeing is roughly what's explained in Wikipedia: https://en.wikipedia.org/wiki/ISO_week_date
The year number of the ISO week very often differs from the Gregorian year number for dates close to 1 January. For example, 29 December 2014 is ISO 2015-W01-1, i.e., it is in year 2015 instead of 2014.
 
Top Bottom