-1

I'm calculating the difference between two dates (the current date and a date in the database). I want to display the difference in days and hours between the dates, but when the day-difference is 0 I don't want to display it. This is my code:

<?php    
$to_time = new \DateTime($database_time);
$from_time = new \DateTime();
echo $from_time->diff($to_time)->format("%d %H");
?>

Output should be, for example:

 > 50 days and 4 hours 
 > 1 day and 7 hours //and not 1 dayS 
 > 6 hours //and not 0 days and 6 hours

There are two issues with my own code: the first one is that it always display the number of days. The second one is that it is just a format. For example when the difference is 2 months, 6 days and 2 hours it displays: 6 days and 2 hours. But it should be 68 days and 2 hours (because of the two months).

Can't get it work with other codes I found. Thanks in advance!

Jordy
  • 4,719
  • 11
  • 47
  • 81
  • The code is working fine. "d" will give you the number of days. Read about the format here: http://php.net/manual/en/function.date.php – Ron Dadon May 22 '15 at 12:10
  • 1
    And "diff" is returning a DateInterval object, not DateTime, read about DateInterval object here: http://php.net/manual/en/class.dateinterval.php – Ron Dadon May 22 '15 at 12:12
  • possible duplicate of [How to calculate the difference between two dates using PHP?](http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php) – Narendrasingh Sisodia May 22 '15 at 12:25

1 Answers1

1

Try this..

   $seconds = strtotime("2012-10-10 02:40:03") - strtotime("2010-12-25 05:15:02");

echo $days    = floor($seconds / 86400);
echo "</br>";
echo $hours   = floor(($seconds - ($days * 86400)) / 3600);
echo "</br>";
echo $minutes = floor(($seconds - ($days * 86400) - ($hours * 3600))/60);
echo "</br>";
echo $seconds = floor(($seconds - ($days * 86400) - ($hours * 3600) - ($minutes*60)));
Deenadhayalan Manoharan
  • 5,436
  • 14
  • 30
  • 50