php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #69338 strtotime does not note, that a month can have 5 weeks
Submitted: 2015-03-31 08:59 UTC Modified: 2015-03-31 09:18 UTC
Votes:1
Avg. Score:5.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: igor875126 at gmail dot com Assigned:
Status: Not a bug Package: Date/time related
PHP Version: Irrelevant OS: Linux
Private report: No CVE-ID: None
 [2015-03-31 08:59 UTC] igor875126 at gmail dot com
Description:
------------
The function strtotime('-1 month') does substract 4 weeks, but should substract THE NUMBER OF DAYS IN MONTH

Example:

Our current date: 31.03.2015 // contains 5 weeks

$minusonemonth = date('Ymd', strtotime('-1 month'));

Returns:
20150303
It seems that "strtotime('-1 month');" just substracts 4 weeks

Solution:
-1 month should substract number of days in the month

Workarround:
$minusonemonth = date('Ymd', strtotime('-' . date('t') . ' day'));

Test script:
---------------
$minusonemonth = date('Ymd', strtotime('-1 month'));


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2015-03-31 09:18 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2015-03-31 09:18 UTC] requinix@php.net
"-1 month" does exactly what it says: subtract 1 from the month number. The result is February 31st. Of course that's invalid so PHP "wraps" the date around, as it does with its other date/time parsing functions. Thus March 3rd.

If you want to subtract the number of days in the month then you need to literally subtract the number of days in the month.
  strtotime(date("-t") . " days"); // -31 days from Mar 31 = Feb 28
Keep in mind that you'll still get weird results with that method; Mar 1 gives
  strtotime(date("-t") . " days"); // -31 days from Mar 1 = Jan 29
http://3v4l.org/D3ebX

So unless that's the behavior you want, you'll have to figure out exactly what you want to get in those kinds of edge cases - and accept that you may have to write code to explicitly support it.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri May 17 11:01:34 2024 UTC