Ricardo Capistran
Ricardo Capistran

Reputation: 161

Adding and removing a year from date

I would like to add and remove a year from a date

I have this code:

$yearbefore = date("Y",strtotime("-1 year"));
$yearnext = date("Y",strtotime("+1 year"));

This will add and remove a year from current date, but what if I want it from another year in a var?

$year = "2010";

How can this be done?

Upvotes: 0

Views: 2306

Answers (2)

uptownhr
uptownhr

Reputation: 672

$date = '2013-11-01';
$seconds_in_year = 31536000;
echo date('y-m-d', strtotime($date) - $seconds_in_year);

Upvotes: 0

kero
kero

Reputation: 10638

You can use strtotime as well but need to set day and month by default - since you need only the year that should be no problem.

$year = intval($year); //make sure it is an integer
$yearbefore = date("Y", strtotime("01/01/$year -1 year"));
$yearafter  = date("Y", strtotime("01/01/$year +1 year"));

But when you are sure, the given year is already in the right format, you can just decrement/increment it.

$year = intval($year);
$yearbefore = $year - 1;
$yearafter  = $year + 1;

Upvotes: 1

Related Questions