24

I am using 2 timestamps in my table, which is

starttime    datatype - timestamp and as current timestamp
endtime      datatype - timestamp and default as 0000-00-00 00:00:00

How to calculate the difference between 2 timestamps in PHP

starttime:   2016-11-30 03:55:06
endtime:     2016-11-30 11:55:06
wittich
  • 2,079
  • 2
  • 27
  • 50
user6582683
  • 315
  • 1
  • 4
  • 15
  • 1
    Hi, what interval do you want (seconds or hours or days)? – Rav Dec 01 '16 at 07:56
  • Possible duplicate of [How do I find the hour difference between two dates in PHP?](http://stackoverflow.com/questions/3763476/how-do-i-find-the-hour-difference-between-two-dates-in-php) – Rav Dec 01 '16 at 08:00
  • 2
    Possible duplicate of [How to get time difference in minutes in PHP](http://stackoverflow.com/questions/365191/how-to-get-time-difference-in-minutes-in-php) – chus Dec 01 '16 at 08:09

7 Answers7

39

Any procedural way should be avoided.
Use OOP method for date time difference:

$datetime1 = new DateTime('2016-11-30 03:55:06'); // start time
$datetime2 = new DateTime('2016-11-30 11:55:06'); // end time
$interval = $datetime1->diff($datetime2);
echo $interval
     ->format('%Y years %m months %d days %H hours %i minutes %s seconds');
     // 00 years 0 months 0 days 08 hours 0 minutes 0 seconds

You can setup difference format as per your needs.

%Y - use for difference in year
%m - use for difference in months
%d - use for difference in days
%H - use for difference in hours
%i - use for difference in minutes
%s - use for difference in seconds

You can remove any of the above values as per your need. For example, if you only are interested in hour difference, and you know that difference can't be more than 24 hours, then use only %H.

If you want to have total difference in seconds, then you can use:

echo $difference_in_seconds 
     = strtotime('2016-11-30 11:55:06') - strtotime('2016-11-30 03:55:06');
// 28800

Depends upon your need and the final format in which you want to have time difference.

For reference check: https://www.php.net/manual/en/datetime.diff.php

wittich
  • 2,079
  • 2
  • 27
  • 50
Abhay Maurya
  • 11,819
  • 8
  • 46
  • 64
  • 4
    Why should an OOP approach be used instead of a procedural one? – Derrick Miller Aug 28 '19 at 17:33
  • @DerrickMiller OOP in general is better than procedural for numerous reasons, that is why we should always try to adopt OOP whenever we can, if possible to write only in OOP. Here is a link which might help you understand why is that https://www.reddit.com/r/PHP/comments/7tzazd/procedural_vs_object_oriented_im_new_to_oop/ – Abhay Maurya Aug 29 '19 at 07:06
19

You can convert your timestamps to unix timestamp (time in seconds) using php strtotime and then take the difference. You now have the difference in time in seconds and can convert to what you need...hours, min, days

http://php.net/manual/en/function.strtotime.php

ex:

$ts1 = strtotime($start);
$ts2 = strtotime($end);     
$seconds_diff = $ts2 - $ts1;                            
$time = ($seconds_diff/3600);
bio_sprite
  • 438
  • 2
  • 14
2

The simplest answer(for me of course) is here

function dateDifference($date_1 , $date_2 , $differenceFormat = '%a' )
{
    $datetime1 = date_create($date_1);
    $datetime2 = date_create($date_2);

    $interval = date_diff($datetime1, $datetime2);

    return $interval->format($differenceFormat);

}

In this case date_create() function creates the DateTime object

AlexKh
  • 546
  • 2
  • 9
  • 20
1

I have created one function which helps you to get Hours, Minutes and Days from the two Unix timestamps by just passing type as 3rd parameter.

public function diffBtwTimesAsPerType($start, $end, $returnType=1) {
    $seconds_diff = $start - $end;
    if($returnType == 1){
        return $seconds_diff/60;//minutes
    }else if($returnType == 2){
        return $seconds_diff/3600;//hours
    }else{
        return $seconds_diff/3600/24; //days
    }
}

echo "<br> Minutes = ".diffBtwTimesAsPerType(1593714600, 1593541800, 1);//minutes
echo "<br> Hours = ".diffBtwTimesAsPerType(1593714600, 1593541800, 2);//hours
echo "<br> Days = ".diffBtwTimesAsPerType(1593714600, 1593541800, 3);//days
Atul Baldaniya
  • 761
  • 8
  • 14
0

@atul-baldaniya, I've modified your solution to avoid negative values and return integer results instead of decimal values.

function diffBtwTimesAsPerType($start, $end, $returnType=1) {
    $seconds_diff = $end - $start;
    if($returnType == 1){
        return round($seconds_diff/60);//minutes
    }else if($returnType == 2){
        return round($seconds_diff/3600);//hours
    }else{
        return round($seconds_diff/3600/24); //days
    }
}
0

If you need the difference in 00:00:00 (Hours, Minutes, Seconds) format, you can use this function.

I used sprintf() because of adding zero before one digit results.

function timeDifference($start, $stop){
    
$diff = strtotime($stop) - strtotime($start);
$fullHours   = floor($diff/(60*60));
$fullMinutes = floor(($diff-($fullHours*60*60))/60);
$fullSeconds = floor($diff-($fullHours*60*60)-($fullMinutes*60));

return sprintf("%02d",$fullHours) . ":" . sprintf("%02d",$fullMinutes) . ":" . sprintf("%02d",$fullSeconds);
}
-1

try this code, tested on phpfiddle.org :-

function timestampdiff($qw,$saw)
{
    $datetime1 = new DateTime("@$qw");
    $datetime2 = new DateTime("@$saw");
    $interval = $datetime1->diff($datetime2);
    return $interval->format('%Hh %Im');
}
echo timestampdiff('1524794340', '1524803100');