How to calculate difference between two dates in PHP

by  
Share:
Calculating difference between two dates in php

One of the most common scenarios that I come across is calculate difference between two dates in PHP. In this tutorial we will learn to calculate date difference in various format like 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. I have complied a list of common date and time related problems in  The ultimate PHP date cheatsheet.

We neeed to set our time zone before we get started. To set the time zone use the code below. You can set time zone as per your geo location.

<?php
date_default_timezone_set('Asia/Kolkata');
?>

Days difference between two dates

Let’s say we need to find the number of days left for an upcoming event which is on 2021-07-16 and the current date is 2021-07-14, the result will be +2 days ( as we are looking ahead). Take a look at the code below to calculate the days.

<?php
$date1 = new DateTime("2021-07-14");
$date2 = new DateTime("2021-07-16");
$diff = $date1->diff($date2);
// will output 2 days
echo $diff->days . ' days '; ?>

The DateTime::diff variable $diff object has lots of fields that we need to look into.

DateInterval Object
(
    [y] => 0 // year
    [m] => 0 // month
    [d] => 2 // days
    [h] => 0 // hours
    [i] => 0 // minutes
    [s] => 0 // seconds
    [invert] => 0 // positive or negative 
    [days] => 2 // total no of days

)

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

<?php
$date1 = new DateTime("2021-07-14");
$date2 = new DateTime("2021-07-10");
$diff = $date1->diff($date2);
// this will output 4 days                           
echo $diff->days .' days ';

// if you want to check for minus
echo ($diff->invert == 1) ? ' - ' . $diff->days .' days '  : $diff->days .' days ';

?>

Date Time difference in custom format

One of the most common situation you will come across to display your age in format 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.

 function get_format($df) {

    $str = '';
    $str .= ($df->invert == 1) ? ' - ' : '';
    if ($df->y > 0) {
        // years
        $str .= ($df->y > 1) ? $df->y . ' Years ' : $df->y . ' Year ';
    } if ($df->m > 0) {
        // month
        $str .= ($df->m > 1) ? $df->m . ' Months ' : $df->m . ' Month ';
    } if ($df->d > 0) {
        // days
        $str .= ($df->d > 1) ? $df->d . ' Days ' : $df->d . ' Day ';
    } if ($df->h > 0) {
        // hours
        $str .= ($df->h > 1) ? $df->h . ' Hours ' : $df->h . ' Hour ';
    } if ($df->i > 0) {
        // minutes
        $str .= ($df->i > 1) ? $df->i . ' Minutes ' : $df->i . ' Minute ';
    } if ($df->s > 0) {
        // seconds
        $str .= ($df->s > 1) ? $df->s . ' Seconds ' : $df->s . ' Second ';
    }

    echo $str;
}

Using the the function: Take your birth date and current date, pass the datetime::diff object to the custom function get_format() and print the result.

<?php
$date1 = new DateTime("1990-04-02");
$date2 = new DateTime("now");
$diff = $date1->diff($date2);
echo get_format($diff);

// will output something like this below ( the time section will be variable )
// 30 Years 04 Months 12 Days 18 Hours 6 Minutes 26 Seconds 
?>

Time difference in minutes

If you need to calculate the sum total of minutes between two dates. The formula to use is TOTAL_MINUTES = (days * 24 * 60 ) + minutes.

<?php
$date1 = new DateTime("2015-02-14 15:29:00");
$date2 = new DateTime("now");
$diff = $date1->diff($date2);
// 38 minutes to go [number is variable]
echo ( ($diff->days * 24 ) * 60 ) + ( $diff->i ) . ' minutes';
// passed means if its negative and to go means if its positive
echo ($diff->invert == 1 ) ? ' passed ' : ' to go ';
?>

Time difference in seconds

If you need to calculate the sum total of seconds between two dates. The formula to use here is TOTAL_SECONDS = (days * 24 * 60 ) + (minutes * 60) + sec.

<?php
$date1 = new DateTime("2015-02-14 15:29:00");
$date2 = new DateTime("now");
$diff = $date1->diff($date2);
// 3036 seconds to go [number is variable]
 echo ( ($diff->days * 24 ) * 60 ) + ( $diff->i * 60 ) + $diff->s . ' seconds';
// passed means if its negative and to go means if its positive
echo ($diff->invert == 1 ) ? ' passed ' : ' to go ';
?>

View Demo

Share to download the Source Codes for FREE!
We're glad to give free downloads, but we need your love to carry on making that.
Please support us by sharing the page.

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

deazure on

hello i try to download yr source. i share with my facebook but notihing
how i can

thanks

Reply
Shahrukh Khan on

Please click in the download link again. it will open the link.

Reply
shahwal on

brother awesome post u have posted…

i want to know that
how to create a sub domain for a particular website like u have
“https://aarafacademy.com”
and
“demos.aarafacademy.com”

please help me….

Reply
Shahrukh Khan on

To create a sub domain, open your hosting control panel, under Domains box, you will find subdomains menu. all the forms under that are self-explanatory. hope this helps.

Reply
pravin on

is it possible to setup sub domain for main domain in “bigrock.in”

Shahrukh Khan on

Yes that is possible. contact your hosting provider for best info regarding this.

Mahather on

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 );

Reply
Shahrukh Khan on

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.

diff($date2);
// will output results in days. if you need to get more info var_dump($diff);
echo $diff->days . ' days ';
?>

Reply
GeoMaster on

hi , i need to show site registred user birthday between two month , how this make please help mi… sorry bad english…

Reply
helalreza on

I want to difference end_time – start_time and need that result in second.

Reply
nurmuhammad on

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;
}

Reply
Ahmed on

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 .

Reply
Shahrukh Khan on

change the timezone to your region format.

Reply
Sunil on

Hi Shahrukh this is sunil, i want cod for email form to store in database and mail to be sent to specified mail id

Reply
Shahrukh Khan on

try the ajax contact form tutorial. it is very much related.

Reply
Hardik Gadhiya on

Hi,

I have a past date like 20-07-2018. And I want to fetch current month date and last month date using that past date.

How can I do it?

Thank you.

Reply
Shahrukh Khan on

like exactly what result you want to achieve

Reply
Amit Shee on

Thanks for sharing this code with us. This is really help us a lot. I have used this code and it works fine. I have resolved my project issues finally. Thanks

Reply
Shahrukh Khan on

you are welcome

Reply
Vikas Tyagi on

This script is just awesome, thanks for sharing it.

Reply
Shahrukh Khan on

you are welcome.

Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.