首页 > 解决方案 > 奇怪的php日期strtotime问题

问题描述

我在 PHP 中使用“date”函数和“strtotime”看到了一个奇怪的问题。

echo date('m/d/Y h:i:s a', time())."<br>";       //returns 04/29/2021 12:26:30 pm
echo date('M Y', strtotime('-5 months'))."<br>"; //returns Nov 2020
echo date('M Y', strtotime('-4 months'))."<br>"; //returns Dec 2020
echo date('M Y', strtotime('-3 months'))."<br>"; //returns Jan 2021
echo date('M Y', strtotime('-2 months'))."<br>"; //returns Mar 2021
echo date('M Y', strtotime('-1 months'))."<br>"; //returns Mar 2021
echo date('M Y')."<br>";                         //returns Apr 2021

我的服务器时间是正确的,如第一行所示,但为什么 strtotime('-2 months') 和 strtotime('-1 months') 返回相同的值(2021 年 3 月)两次?

提前致谢

标签: phpdatestrtotime

解决方案


您将在 4 月 29 日测试此功能 echo date('M Y', strtotime('-2 months'))。它将返回 2021 年 2 月 29 日 - 一个不存在的日期,因此它默认为 2 月 (28) 的最后一天并加 1 以获得 3 月 1 日。

...我在这里有一个解决方案,但与您下面的解决方案相比,它有点像黑客,所以我删除了它以支持您的解决方案


推荐阅读