Social Icons

Tuesday, April 8, 2014

Calculate difference between two dates in php

Suppose you have two dates as some start date and end date. You have to find the difference between those dates in years, months and days. It can be easily done by converting the date into timestamp value using strtotime function.

Say, you have two dates as follows:

$date1 = "2012-04-24";
$date2 = "2013-05-28";

Convert these dates into timestamp and subtract these.

$difference = abs(strtotime($date2) - strtotime($date1));

Now, you can calculate difference in years, month and days as follows:-

$years = floor($difference / (365*60*60*24));
$months = floor(($difference - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($difference - $years * 365*60*60*24 - $months * 30*60*60*24) / (60*60*24));

Another way to do it using OOP approach as follows:-

$date1 = new DateTime("2012-04-24");
$date2 = new DateTime("2013-05-28");

$interval = $date1->diff($date2);
echo $interval->y ." years ".$interval->m." months ".$interval->d." days";

Total Pageviews