php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #71687 Adding one year to a leap day produces incorrect date
Submitted: 2016-02-29 10:41 UTC Modified: 2016-02-29 12:05 UTC
From: kungfutse at hotmail dot com Assigned:
Status: Not a bug Package: Date/time related
PHP Version: 5.6.18 OS: Linux
Private report: No CVE-ID: None
 [2016-02-29 10:41 UTC] kungfutse at hotmail dot com
Description:
------------
When adding one year (new DateInterval('P1Y')) to a leap day (new DateTime('2016-02-29')) results in incorrect date. It should return 2017-02-28 but returns 2017-03-01 instead.

For comparison, MariaDB 10 returns the correct date when doing SELECT DATE_ADD(DATE('2016-02-29'), INTERVAL 1 YEAR);

Test script:
---------------
var_dump( (new \DateTime('2016-02-29'))->add(new \DateInterval('P1Y')) );

Expected result:
----------------
object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2017-02-28 00:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(15) "Europe/Helsinki"
}


Actual result:
--------------
object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2017-03-01 00:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(15) "Europe/Helsinki"
}


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-02-29 12:05 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2016-02-29 12:05 UTC] requinix@php.net
PHP's* date arithmetic for P1Y literally increments the year by one. That would create the date 2017-02-29 which overflows into 2017-03-01. This method doesn't appear to be suitable for your needs; you may have to do the date math yourself, such as by comparing the number of days in the beginning and end months, seeing that 29 is beyond next year's 28, and creating the date {$year+1}-{$month}-{$number_of_days} = 2017-02-28 manually.

* Python, Perl, and IIRC Linux's `date` do this overflow stuff too.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon May 20 18:01:36 2024 UTC