- Instant help with your Php coding problems

PHP date difference

If you want to get the difference between dates or time values, then you first need to get the values in the same format. The best way is to convert both dates into Unix timestamp format. In this case, the date and time information is stored as an integer so we can calculate the difference easily. You can get the Unix timestamp in various ways as you can see below:

<?php
  // Get current time 
  $date1 = time(); 
 
  // Get the timestamp of 2006 October 20
  $date2 = mktime(0,0,0,10,20,2006);
?>

Now as you have the values getting the difference is quite easy. However the result will be an integer value, but you probably want to get it in days, hours, and minutes. To do so we need to convert back our int value into a usable date format. We know that the difference is in seconds so we can get how many full days it is. To get it we use the following code:

<?php
   $dateDiff = $date1 - $date2;
   $fullDays = floor($dateDiff/(60*60*24));
   echo "Differernce is $fullDays days";   
?>

We used the floor function as we want to get only the complete days. Besides this, the 60*60*24 represents that a day has 24 hours and each hour has 60 minutes and each minute has 60 seconds.

As the next step, we need to get how many hours are still present in the remaining seconds.  So from the original difference, we need to remove the complete days in seconds, and from the remaining value, we can calculate the full hours similar to as we calculated the full days. Repeating these steps for minutes as well at the end we get the difference between the original dates. The complete calculation looks like this:

<?php
   $dateDiff    = $date1 - $date2;
   $fullDays    = floor($dateDiff/(60*60*24));
   $fullHours   = floor(($dateDiff-($fullDays*60*60*24))/(60*60));
   $fullMinutes = floor(($dateDiff-($fullDays*60*60*24)-($fullHours*60*60))/60);
   echo "Differernce is $fullDays days, $fullHours hours and $fullMinutes minutes.";   
?>

Share "PHP date difference" with your friends