Search code examples
phpphp-7isodate

setISODate work that way?


I am testing these cases:

$date = new \DateTime();
echo($date->format('Y.m.d')) . PHP_EOL;

$date->setISODate(2018, 1, 1);
echo($date->format('Y.m.d')) . PHP_EOL;

$date->setISODate(2019, 1, 1);
echo($date->format('Y.m.d')) . PHP_EOL;

$date->setISODate(2020, 1, 1);
echo($date->format('Y.m.d')) . PHP_EOL;

Ouput:

2017.08.17
2018.01.01
2018.12.31
2019.12.30

I understood that it would show this:

2017.08.17
2018.01.01
2019.01.01
2020.01.01

Why does that happen?

Surely there is something I did not quite understand.


Solution

  • The arguments are year, week, dayofweek. PHP's week starts on Monday, and week 1 of a year is the first week that has at least 4 days in January.

    In 2018, the year starts on Monday, so week 1 starts on January 1, and that's day 1 of the week.

    In 2019, the year starts on Tuesday, so week 1 starts on Monday, December 31, 2018, and that's day 1 of the week.

    In 2020, the year starts on Wednesday, so week 1 starts on Monday, December 30, 2019, so that's day 1 of the week.