pistou
pistou

Reputation: 2867

PHP DateTime modify gives wrong date on leap year

I'm using PHP's DateTime object to manipulate dates. I found a strange case where the result date seems wrong:

$dt = new DateTime('2020-02-29 23:59:59');
$dt->modify('-1 year');
echo $dt->format('Y-m-d H:i:s');

This code gives 2019-03-01 23:59:59 instead of 2019-02-28 23:59:59. I believe it is due to 2020 having a Feb. 29th yet I have no clue how to fix this issue.


Note that the modifier can be anything, not just -1 year. A solution that would isolate the year number minus one wouldn't fit my needs.

Upvotes: 1

Views: 949

Answers (1)

pistou
pistou

Reputation: 2867

I figured out myself a work around that seems to work.

I noted that things work well with first day of the month:

$dt = new DateTime('2020-02-01 00:00:01');
$dt->modify('-1 year');
echo $dt->format('Y-m-d H:i:s'); // 2019-02-01 00:00:01

From this statement, I just added a few steps when I need to manipulate "end of the month" dates:

$dt = new DateTime('2020-02-29 23:59:59');
$dt->modify('first day of this month');
$dt->modify('-1 year');
$dt->modify('last day of this month');
echo $dt->format('Y-m-d H:i:s'); // 2020-02-28 23:59:59

Upvotes: 3

Related Questions