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.

5 Answers 5

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

Replace "+2 years" as required.

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

2
  • @NullUserException: Looks pretty obvious that you'd replace 2 with N, and that $timestamp contains the proper timestamp. Nowhere does it say in Jeff's code that $timestamp = now. Mar 2, 2011 at 20:19
  • It's an example ... with the proviso, "replace +2 years as required" :P Mar 2, 2011 at 20:20
9
$date = new DateTime();
$date->add(new DateInterval('P10Y'));

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

7
  • +1, didn't know that one! On a sidenote, do you know some good text/book/tutorial on the new stuff to v5.3? Except official manual. Mar 2, 2011 at 20:18
  • Not offhand. The php site has a good changelog/migration tutorial, though. I tend to avoid PHP books, because they're either hideously out of date, poorly written (e.g. lead you to write very bad insecure code), or just wildly wrong.
    – Marc B
    Mar 2, 2011 at 20:20
  • Not fully correct: DateTime is in since 5.2, only DateInterval was added for 5.3.
    – tobyS
    Mar 2, 2011 at 20:26
  • This is a good solution, I'm just sorry we don't have php 5.3.
    – Onema
    Mar 2, 2011 at 20:40
  • In that case, the strtotime() options in the other answers will work for you.
    – Marc B
    Mar 2, 2011 at 20:42
1

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);`
1
  • Now days you should use a library like Carbon to do all this time/date staff in php. It makes it a joy to work with dates.
    – George D.
    Jul 9, 2016 at 9:53
1
$date    = "1998-08-14";

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

echo $newdate;

echos

2000-08-14
-1

If for any reason you already have the actual timestamp, you could just add 31536000 to it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.