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
 [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

Add a Patch

Pull Requests

Add a Pull Request

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: Thu Mar 28 20:01:28 2024 UTC