PHP DateTime返回非预期结果



我想在PHP中获得-2个月的日期。大多数时候,结果是好的,但是有一天,结果是错误的。

$d = 1409436000;    // 31-8-2014
$d1 = new DateTime(date("d-m-Y", $d));
$d1->modify("-2 month");
echo $d1->format("d-m-Y");
// expected : 30-06-2014
// got      : 01-07-2014
我当前的PHP版本是:5.6.23-0+deb8u1我没有对TimeZone做任何配置。

So:为什么我得到这个结果?这是因为八月和七月有31天?还是phpversion上的当前错误?时区?

谢谢=)

根据评论和链接,我这样解决了我的问题:

$d = 1409436000;    // 31-8-2014
$d1 = strtotime("first day of this month", $d);
$d1 = strtotime("-2 month", $d1);
$d1 = strtotime("last day of this month", $d1);
echo date("d-m-Y", $d1);
  • 确保您将得到正确结果的方法是采取你约会的第一天。
  • 制作你需要的东西。
  • 获取当前月份的最后一天。

问题是:我试着让"31/08/2014 -2 month"等于"31/06/2014"。

31/06/2014 =>此日期不存在,PHP会将其转换为"01/07/2014"

最新更新