PHP date difference


Home - Tutorials - Date and time

In this tutorial I will show you how to calculate difference between dates and times in PHP.

Tutorial info:


Name:PHP date difference
Total steps:1
Category:Date and time
Level:Beginner

Bookmark PHP date difference



Bookmark and Share

Step 1 - PHP date difference


PHP date difference

If you want to get the difference between to 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:

Code:
  1. <?php
  2. // Get current time
  3. $date1 = time();
  4.  
  5. // Get the timestamp of 2006 October 20
  6. $date2 = mktime(0,0,0,10,20,2006);
  7. ?>

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:

Code:
  1. <?php
  2. $dateDiff = $date1 - $date2;
  3. $fullDays = floor($dateDiff/(60*60*24));
  4. echo "Differernce is $fullDays days";
  5. ?>

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 ours and each hour has 60 minutes and each minute has 60 seconds.

As 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:

Code:
  1. <?php
  2. $dateDiff = $date1 - $date2;
  3. $fullDays = floor($dateDiff/(60*60*24));
  4. $fullHours = floor(($dateDiff-($fullDays*60*60*24))/(60*60));
  5. $fullMinutes = floor(($dateDiff-($fullDays*60*60*24)-($fullHours*60*60))/60);
  6. echo "Differernce is $fullDays days, $fullHours hours and $fullMinutes minutes.";
  7. ?>







Tags: php date diffrence, php time difference, date diffrence

PHP date difference - Table of contents
Step 1 - PHP date difference


Follow phpf1 on Twitter




F1 Site Family
AJAX F1
CSS F1
Database F1
Flash F1
HTML F1
Java F1
JavaScript F1
PhotoShop F1
PHP F1
Scripts F1
Tutorial F1
Windows F1

Total time: 0.0338