I try to get a calculable days/weeks number: how many days/weeks passed from some date.
date_default_timezone_set('Europe/Moscow');
$beforDate=DateTime::createFromFormat('Y-m-d G:i:s', '1900-01-01 00:00:00'); // monday, 1-st Jan of 1900
$afterDate=DateTime::createFromFormat('Y-m-d G:i:s', '2021-02-08 00:00:42');
$dtInterval = $beforDate->diff($afterDate);
$daysPassed = $dtInterval->days;
echo "days passed if target date have 42 seconds from midnight: $daysPassed" . PHP_EOL;
$afterDate=DateTime::createFromFormat('Y-m-d G:i:s', '2021-02-08 00:00:43');
$dtInterval = $beforDate->diff($afterDate);
$daysPassed = $dtInterval->days;
echo "days passed if target date have 43 seconds from midnight: $daysPassed" . PHP_EOL;
In this example, I see a very weird result: if I add only one second after midnight to the target date, I get plus one day. Code result:
- days passed if target date have 42 seconds from midnight: 44232
- days passed if target date have 43 seconds from midnight: 44233
Is it a bug or I am just stupid?
Tested on PHP7.2, PHP7.4 (Ubuntu 18.04) and it is irrelevant to timezone set (I tried to set UTC - no difference)
If it's a bug, How you would advise a fast enough method of getting the Integer number of days/weeks passed from some date?
Updated:
Just realized: the error appears if I set default timezone to
date_default_timezone_set('Europe/Moscow');
But I cannot understand how the timezone can affect it? Because a year has the same number of days in any time zone
Found another incorrect behaviour:
$beforDate=DateTime::createFromFormat('Y-m-d G:i:s', '1900-01-01 00:00:00');
$beforDate->setTimezone(new DateTimeZone('UTC'));
$afterDate=DateTime::createFromFormat('Y-m-d G:i:s', '2021-02-08 00:00:00');
$afterDate->setTimezone(new DateTimeZone('UTC'));
$dtInterval = $beforDate->diff($afterDate);
$daysPassed = $dtInterval->days;
echo "1. days passed: $daysPassed" . PHP_EOL;
$afterDate=DateTime::createFromFormat('Y-m-d G:i:s', '2021-02-08 00:50:00');
$afterDate->setTimezone(new DateTimeZone('UTC'));
$dtInterval = $beforDate->diff($afterDate);
$daysPassed = $dtInterval->days;
echo "1. days passed if 50 minutes added to target date: $daysPassed" . PHP_EOL;
Have output:
- days passed: 44232
- days passed if 50 minutes added to target date: 44233