Calculating difference between two dates in php

14

One of the most common scenarios that I come across is calculating difference between two dates. I was doing back to back projects and I came across similar situation in many places. So I thought why not share this important piece of code with all of you. In this tutorial I will be explaining the technique for calculating difference between two dates in php. You can use this technique to get total days, minutes, seconds months, years.

View Demo

Using PHP DateTime Class

I am using PHP DateTime Class to assign dates. It will work on PHP 5.2 and above. For calculating the difference between two dates i have used DateTime::diff which will work on PHP 5.3 and above. If you are using lower version, it’s time for you to upgrade. If you want some other date time snippet check these one Change date format mm/dd/yyyy to yyyy-mm-dd in php Print last month date range using php Print next month date range using php

Don’t forget to set your timezone before you start working on the date and time. To set the timezone use the code below. All the list of timezoone can be found here.

 

Days difference between two dates

Let’s say you have find days difference for an upcoming event which is on 2015-02-16 and the current date is 2015-02-14, the result will be +2 days ( as we are looking ahead). Take a look at the code below to calculate the days.

If you print the $diff object you will see the following.

Let’s take another situation where you need to find the number of days when a customer booked an order. Suppose today’s date is 2015-02-14 and customer booked the order on 2015-02-10 so the answer will be -4 days. Take a look at the code below.

Date Time difference in custom format

Another common/popular scenario is when you want to display the duration you lived since your birthday, the format is like 20 years 10 months 6 days 10 hours 15 minutes 10 seconds. To achieve this take a look at the code below. I have made a custom function get_format() to return a formatted result.

How to use the function: feed your birthday/date and today’s/custom date, pass the datetime::diff object to the custom function get_format() and print the result.

Time difference in minutes

If you need to calculate the sum total of minutes between two dates use the code below. The formula to use here is TM = (days * 24 * 60 ) + minutes where TM is total minutes, days is total days difference, and minutes is remaining minutes.

Time difference in seconds

If you need to calculate the sum total of minutes between two dates use the code below. The formula to use here is TM = (days * 24 * 60 ) + (minutes * 60) + sec where TM is total minutes, days is total days difference, and minutes is remaining minutes, and sec is the remaining seconds.

If you guys have find any bug or have any other alternate suggestion share with us.

View Demo
Download

Share.
 

About Author

Entrepreneur & Dreamer

I am a passionate Software Professional, love to learn and share my knowledge with others.

Software is the hardware of my life.

14 Comments

  1. brother awesome post u have posted…

    i want to know that
    how to create a sub domain for a particular website like u have
    “www.thesoftwareguy.in”
    and
    “demos.thesoftwareguy.in”

    please help me….

  2. bro really this is very helpful for me and awesome post .. can you help me I want to get the difference in date time from SQL database ….. I’ve date and time in SQL Database so I want get the difference , I’ve tried below code but it doesn’t work

    $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC
    $$dbdate= $row[bdate];
    $date1 = new DateTime($dbdate );

    • your code is totally wrong.
      first of all make sure you have one $ not $$ which you have given in second line.
      now say in you database table you have two column start_date and end_date and you have that those in a variable called $results ( I am not going to show how to make the DB calls to fetch results, you can use whatever method you want.). Then try to get the difference using this code.

      < ?php $date1 = new DateTime($results["start_date"]); $date2 = new DateTime($results["end_date"]); $diff = $date1->diff($date2);
      // will output results in days. if you need to get more info var_dump($diff);
      echo $diff->days . ' days ';
      ?>

  3. Copy and pest this

    Seconds

    document.getElementById(‘calcBtn’).onclick = function(){
    var startTime = document.getElementById(‘startTimeInput’).value;
    var endTime = document.getElementById(‘endTimeInput’).value;
    var result = getDeltaSeconds(startTime, endTime);
    document.getElementById(‘result’).innerHTML = result + ‘ sec’;
    }
    function getDeltaSeconds(startTime, endTime){
    var startTimeSeconds = getSeconds(startTime);
    var endTimeSeconds = getSeconds(endTime);
    return endTimeSeconds – startTimeSeconds;
    }
    function getSeconds(timeString){
    var parts = timeString.split(‘ ‘);
    var time = parts[0];
    var ampm = parts[1];
    var timeParts = time.split(‘:’);
    var seconds = Number(timeParts[2]) + Number(timeParts[1]*60) + Number(timeParts[0]*60*60);
    return ampm == ‘AM’ ? seconds : seconds + 12*60*60;
    }

  4. hello brother

    thank you for your code . it is very useful for me

    but if i want to change the date format to Arabic Format how can i make that .

Leave A Reply

CommentLuv badge

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.