php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #76175 date function not working properly for Feb month
Submitted: 2018-04-02 05:49 UTC Modified: 2018-04-05 10:29 UTC
From: ansari dot sohail2013 at gmail dot com Assigned:
Status: Not a bug Package: Date/time related
PHP Version: 7.0.29 OS: Windows
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: ansari dot sohail2013 at gmail dot com
New email:
PHP Version: OS:

 

 [2018-04-02 05:49 UTC] ansari dot sohail2013 at gmail dot com
Description:
------------
$d = '30-03-2018';

echo date('Y-m', strtotime('-1 month '.$d));// should give 2018-02
echo date('Y-m', strtotime('-2 month '.$d));// this gives 2018-01


Output:
2018-03
2018-01


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2018-04-02 05:59 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2018-04-02 05:59 UTC] requinix@php.net
30-03-2018 - 1 month  = 30-02-2018 which overflows to 02-03-2018.
30-03-2018 - 2 months = 30-01-2018 which does not need to overflow.

If your application requires special handling around the beginning or end of months then you need to write code for it.
 [2018-04-05 07:34 UTC] ansari dot sohail2013 at gmail dot com
But -1 month should substract by month not by -30 days
 [2018-04-05 09:45 UTC] requinix@php.net
And that's exactly what it did: subtract one month. But there is no such thing as the 30th of February.
Read what I said again.
 [2018-04-05 10:29 UTC] derick@php.net
To obtain your expected output, you can use:

<?php
$d = '30-03-2018';

echo date('Y-m-d', strtotime('last day of -1 month '.$d)), "\n";
echo date('Y-m-d', strtotime('last day of -2 month '.$d)), "\n";
?>

See also "Example #3" at http://php.net/manual/en/datetime.examples-arithmetic.php#example-2530
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun Dec 22 01:01:30 2024 UTC