Sam Stones
Sam Stones

Reputation: 73

PHP How to find the date and time one year and one day ago when it's a leap year

I'm trying to get php to calculate a date that was one year and one day ago. I have this:

$date = date(strtotime('-366 days'));
$oneyear_oneday = date("Y-m-d H:i:s", $date); 

$date = date(strtotime('-1 year'));
$oneyear = date("Y-m-d H:i:s", $date);

However, due to it being a leap year, both $oneyear and $oneyear_oneday provide the same output. Does anyone know how I can calculate this correctly?

ie if it's 3pm on 15th August 2012, I want the output to be 3pm on the 15th August 2011

Upvotes: 0

Views: 901

Answers (5)

J. Bruni
J. Bruni

Reputation: 20492

First, subtract one year. Then, subtract one day from the result:

$date = strtotime('-1 day', strtotime('-1 year'));
$oneyear_oneday = date("Y-m-d H:i:s", $date); 

Upvotes: 0

Basith
Basith

Reputation: 1075

$date = strtotime('2010-01-01 -1 year');
echo date('Y-m-d', $date); 

The output stream looks like,

2009-01-01

Go this Link for more reference

Upvotes: 0

dnagirl
dnagirl

Reputation: 20446

with PHP5.3,

   $date = new DateTime();
   $interval = new DateInterval("P1Y");
   $newdate = $date->sub($interval);

Upvotes: 3

steffen
steffen

Reputation: 17028

Both calculations are correct. But if you want to get the same date, but one year before, you should simply use '-1 year'. The string '-366 days' is only correct in leap years.

Upvotes: 0

GeoffreyB
GeoffreyB

Reputation: 1839

You can try to use mktime()...

Upvotes: 0

Related Questions