添加导致相同日期的时间戳的相对时间?

时间:2016-04-20 16:36:13

标签: php datetime time

// to simplify $timestamp in this example is the unix timestamp of 2016-04-20

考虑这个例子:

strtotime('+1 year', $timestamp); // this returns 2017-04-19

如何让它返回2017-04-20

另一个例子:

strtotime('+1 month', $timestamp); // this returns 2016-05-19

如何让它返回2016-05-20

基本上,我希望相对增加时间,最后得到相同的日期。

3 个答案:

答案 0 :(得分:1)

strtotime('+1 day', strtotime('+1 year', $timestamp));

答案 1 :(得分:1)

$date = date("Y",$timestamp) + 1 //gives you the next year

$date .= "-" . date("m-d",$timestamp) //concantenates on the current month and day

答案 2 :(得分:1)

我可能误解了你的问题,但你可能更善于使用PHP内置的DateTime库,它比标准date()函数更灵活。

所以你可以这样做:

$d = new DateTime();
$d->modify('+1 year');

echo $d->format('Y-m-d'); // Outputs: 2017-04-20

如果要从特定日期创建DateTime对象,可以通过以下方式创建:

$d = DateTime::createFromFormat('Y-m-d', '2016-01-01');
echo $d->format('Y-m-d'); // Outputs 2016-01-01

我相信这就是你所追求的,它比date()更清晰,更容易阅读我的个人观点。

相关问题