PHP: Adding years to a timestamp

2020-02-25 07:19发布

In PHP given a UTC timestamp I would like to add exactly N number of years. This should take into consideration leap years.

Thank you.

4条回答
该账号已被封号
2楼-- · 2020-02-25 07:28
$date    = "1998-08-14";

$newdate = strtotime ( '+2 years' , strtotime ( $date ) ) ;
$newdate = date ( 'Y-m-j' , $newdate );

echo $newdate;

echos

2000-08-14
查看更多
Juvenile、少年°
3楼-- · 2020-02-25 07:31
$date = new DateTime();
$date->add(new DateInterval('P10Y'));

adds 10 years (10Y) to "today". DateTime's only in PHP 5.3, though.

查看更多
Animai°情兽
4楼-- · 2020-02-25 07:42
$newTimestamp = strtotime('+2 years', $timestamp);

Replace "+2 years" as required.

ref: http://php.net/manual/en/function.strtotime.php

查看更多
Evening l夕情丶
5楼-- · 2020-02-25 07:47

One thing you should consider when you do this.

$newTimestamp = strtotime('+2 years', $timestamp);

This adds up 2 years ( 720 or 721 days). In case you just want to keep the same day and month and add 2 extra years in the timestamp

you have to use mktime.

Example

$timestamp = mktime(0, 0, 0, $month, $day, $year+2);`
查看更多
登录 后发表回答