Reputation: 73
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
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
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
Reputation: 20446
with PHP5.3,
$date = new DateTime();
$interval = new DateInterval("P1Y");
$newdate = $date->sub($interval);
Upvotes: 3
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