4

So I have used this method to get the difference between 2 dates.

$diff = abs(strtotime($date2) - strtotime($date1));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

Now, lets say that I want to convert the years and months into days. How do I do that?

Ayie Shindo
  • 43
  • 1
  • 3
  • 1
    You should look into this: http://de2.php.net/DateTime It's much easier. – looper Dec 11 '12 at 13:28
  • duplicate: http://stackoverflow.com/questions/4233605/elegant-way-to-get-the-count-of-months-between-two-dates – GBD Dec 11 '12 at 13:30

2 Answers2

5

Using DateTime this is a piece of cake:

$date1 = new DateTime($date1);
$date2 = new DateTime($date2);

$diff = $date1->diff($date2, true);

echo $diff->format('%a') . ' days';
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • It works for me, but I used it with % echo $diff->format('%a') . ' days'; – Eugene Feb 16 '15 at 13:56
  • @Jack, maybe it's related with version of PHP? I'm using 5.5.9 and it works for me only with %. So it's just a little tip for other guys if it will not work. – Eugene Feb 17 '15 at 11:10
  • 1
    @Eugene Actually, you're right; it needs the % for it to work, my mistake. It's fixed now :) thanks! – Ja͢ck Feb 17 '15 at 11:12
0
$currentDate = date("d-m-Y");
$date1 = date_create("".$joining_date."");
$date2 = date_create("".$currentDate."");
$diff12 = date_diff($date2, $date1);
$hub_days = $diff12->days;
$months = $diff12->m;
$years = $diff12->y;
786
  • 3
  • 2