|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[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'));
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Oct 30 16:00:01 2025 UTC |
"-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.