[php-src] Issue #8275: Function strtotime("-x month", ...) returns different month if the date part is 01-28 or >=29. Additionally different
behaviour for leap and non-leap years
| From: | alex-kalanis | Date: | Wed, 30 Mar 2022 09:29:06 +0000 |
| Subject: | [php-src] Issue #8275: Function strtotime("-x month", ...) returns different month if the date part is 01-28 or >=29. Additionally different behaviour for leap and non-leap years |
||
| Groups: | php.bugs | ||
| Request: | Send a blank email to php-bugs+get-240568@lists.php.net to get a copy of this message | ||
Issue: https://github.com/php/php-src/issues/8275
Comment Author: alex-kalanis
Do not rely on ``
strtotime()` function too much. It depends on system timezones.
Use [`\DateTime`](https://www.php.net/manual/en/class.datetime.php) class
and its methods and other classess and interfaces. For adding and subtracting use especially
[`\DateInterval``](https://www.php.net/manual/en/class.dateinterval.php).
For this problem use another way - calculate amount of days in Feburary. Because exceptions in leap
year where every 100th (2100, 2200) is NOT leap BUT every 400th is (2000, 2400).
```php
<?php
function date_function_check($year, $month, $isleapyear, $timezone = null)
{
$date = \DateTime::createFromFormat('Y-m-d', sprintf('%04d-%02d-%02d', $year,
2, 1), $timezone);
$nextMonth = clone $date;
$nextMonth->add(new \DateInterval('P1M'));
$interval = $date->diff($nextMonth);
$status = '';
if ($interval->days < 29) {
$status = 'not';
}
echo sprintf('The year %04d is %s leap %s', $year, $status, PHP_EOL);
}
```
This example code may need a bit debug, I wrote it just as proof-of-concept.