添加六个月的php


Add six months in php

我想从当前日期算出六个月。

我试过使用:

date('d', strtotime('+6 month', time()));

但它似乎不工作,总是返回01。有更好的方法吗?

谢谢!

我发现使用DateTime更容易:

$datetime = new 'DateTime();
$datetime->modify('+6 months');
echo $datetime->format('d');

$datetime = new 'DateTime();
$datetime->add(new DateInterval('P6M'));
echo $datetime->format('d');

或PHP 5.4+

echo (new 'DateTime())->add(new 'DateInterval('P6M'))->format('d');

如果您仍然希望使用strtotime和date函数而不是DateTime()对象,则可以使用以下方法:

date('d', strtotime('+6 months'));

您可以将DateTime类与DateInterval类结合使用:

<?php
$date = new DateTime();
$date->add(new DateInterval('P6M'));
echo $date->format('d M Y');

您不需要将time()传递给strtotime,因为它是默认的。

除此之外,你的方法是正确的-除了你采取date('d')(这是把一天)而不是date('m')的月,所以echo date('m', strtotime('+6 month'));应该做。

尽管如此,我还是建议使用John所说的DateTime方法。DateTime与"旧的"日期函数相比有几个优点,例如,当UNIX大爆炸后的秒不再适合32位整数时,它们不会停止工作。

示例:

echo date('Y-m-d', strtotime('+6 month' , strtotime(date("2022-07-05"))));

回答:2023-01-05