PHP Strtotime -1月-2个月

12 php strtotime

昨天工作正常,没有更改代码.

echo date("M", strtotime("-3 month", time()) );
echo date("M", strtotime("-2 month", time()) );
echo date("M", strtotime("-1 month", time()) );
echo date("M", time());
Run Code Online (Sandbox Code Playgroud)

它昨天产生的产量正如你所料 - 即4月,5月,6月,7月

今天它与五月五月七月相呼应

有任何想法吗?

提前致谢.

Pas*_*TIN 13

它可能与bug #44073有关

你可以尝试这样的事情:

echo date("M", strtotime("-3 month", strtotime(date("F") . "1")) ) . "\n";
echo date("M", strtotime("-2 month", strtotime(date("F") . "1")) ) . "\n";
echo date("M", strtotime("-1 month", strtotime(date("F") . "1")) ) . "\n";
echo date("M", time()) . "\n";
Run Code Online (Sandbox Code Playgroud)

(解决方案中的注释部分发现strtotime; 直接链接)

并输出:

Apr
May
Jun
Jul
Run Code Online (Sandbox Code Playgroud)

有点日期格式和月份名称的"作弊"以及所有......


Sea*_*ney 8

戈登正确地确定了这个问题,但我想提出另一个有用的解决方案,而不是技术方面.只需在你的strtotime中使用"第一天"或"最后一天".例如,以下这些示例在一个月的31日克服了这个问题:

// Today is May 31st
//All the following return 2012-04-30
echo date('Y-m-d', strtotime("last day of -1 month"));
echo date('Y-m-d', strtotime("last day of last month"));
echo date_create("last day of -1 month")->format('Y-m-d'); 

// All the following return 2012-04-01
echo date('Y-m-d', strtotime("first day of -1 month")); 
echo date('Y-m-d', strtotime("first day of last month"));
echo date_create("first day of -1 month")->format('Y-m-d');
Run Code Online (Sandbox Code Playgroud)


Gum*_*mbo 5

试试这个而不是strtotime

mktime(0, (date("n") - 3 + 12) % 12, 1)
Run Code Online (Sandbox Code Playgroud)

这个想法是取当前月份数 ( date("n")),从中减去您想要的月份数(此处-3),将其加 12,然后取模 12。