php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #50682 strtotime producing incorrect result
Submitted: 2010-01-06 20:28 UTC Modified: 2010-01-07 01:53 UTC
From: keefeg at gmail dot com Assigned:
Status: Not a bug Package: Date/time related
PHP Version: 5.2.12 OS: FreeBSD 6.2
Private report: No CVE-ID: None
 [2010-01-06 20:28 UTC] keefeg at gmail dot com
Description:
------------
strtotime does not handle the "last month" parameter correctly all the time.

Reproduce code:
---------------
---
From manual page: function.strtotime#Description
---
$ny = strtotime("31 December 2009");
echo "this month: " . date('Ym', strtotime("now", $ny)) . "\n";
echo "last month: " . date('Ym', strtotime("last month", $ny)) . "\n";


Expected result:
----------------
I would like it to produce this result:

this month: 200912
last month: 200911


Actual result:
--------------
It prints this result:

this month: 200912
last month: 200912


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-01-06 20:53 UTC] rasmus@php.net
That's because you are asking for the same day last month which doesn't 
exist since November doesn't have 31 days.  November 31 gets normalized 
to Dec 1.  If you are using last/next make sure you feed it a recurring 
starting point.  Like the 1st of the sequence, in this case the 1st of 
the month.
 [2010-01-07 01:37 UTC] keefeg at gmail dot com
I understand your explanation, but the results still seem incorrect.  Under reasonable circumstances even programmers shouldn't have to consider "last month" to be equal to "this month."

In the context of "last month", it should first decrement the month, and then if that particular day (31st of November) does not exist, it should then decrement the day until it reaches a valid day (30th of November).

The way it is now breaks programs in a non-obvious way.  I use that code to daily make a list of archive files to "keep" (now, -1 month, -2 month, -3 month) and on the 31st of December it ended up deleting the november file because it thought "-1 month" was December.

I'll work around using the 1st of the month, but it at least merits a warning in the documentation.

Thanks for PHP, it's incredibly useful!
 [2010-01-07 01:53 UTC] rasmus@php.net
This isn't something we made up.  We are simply following the GNU 
strtotime convention as it is implemented by your command line date 
utility and many others as well.  It is described here:

http://www.gnu.org/software/tar/manual/html_node/Relative-items-in-
date-strings.html#SEC120

Note the second last paragraph that talks about the fuzz in units.  
Whether this should have been done this way or not is debatable, but it 
is a consistent convention and we don't want to stray from that.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon Apr 29 21:01:30 2024 UTC