4

How to find time difference between two dates using PHP.

For example i am having two dates:

start Date : 2010-07-30 00:00:00

end Date : 2010-07-30 00:00:00

In this case how shall i find the time difference using PHP.

hakre
  • 193,403
  • 52
  • 435
  • 836
Fero
  • 12,969
  • 46
  • 116
  • 157
  • possible duplicate of [How to calculate the date difference between 2 dates using php](http://stackoverflow.com/questions/676824/how-to-calculate-the-date-difference-between-2-dates-using-php) – Ben Everard Jul 30 '10 at 10:36
  • 2
    But i need like following : 24hrs 3 minutes 5 seconds. – Fero Jul 30 '10 at 10:39

4 Answers4

7

But i need like following : 24hrs 3 minutes 5 seconds

If you're using PHP 5.3 or better (which you should be), you can use the built in DateTime class to produce a DateInterval which can be formatted easily.

$time_one = new DateTime('2010-07-29 12:43:54');
$time_two = new DateTime('2010-07-30 01:23:45');
$difference = $time_one->diff($time_two);
echo $difference->format('%h hours %i minutes %s seconds');

DateTime was introduced in 5.1, but DateInterval is new to 5.3.

Charles
  • 50,943
  • 13
  • 104
  • 142
4
$d1 = strtotime('2010-07-30 00:00:00');
$d2 = strtotime('2010-07-30 00:00:02');

$diff = $d2 - $d1;

echo $diff;

You will have second in $diff variable

Simpl
  • 49
  • 1
2
<?php
$date1 = $deal_val_n['start_date'];

$date2 = $deal_val_n['end_date'];

$diff = abs(strtotime($date2) - strtotime($date1));

$years = floor($diff / (365*60*60*24)); $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24)); $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

$hours = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24)/ (60*60));

$minuts = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60)/ 60);

$seconds = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60 - $minuts*60));
?>
Fero
  • 12,969
  • 46
  • 116
  • 157
0

Try following code,

<?php
    $date1 = $deal_val_n['start_date'];

    $date2 = $deal_val_n['end_date'];

    $diff = abs(strtotime($date2) - strtotime($date1));

    $years = floor($diff / (365*60*60*24)); $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24)); $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

    $hours = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24)/ (60*60));

    $minuts = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60)/ 60);

    $seconds = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60 - $minuts*60));
    ?>
Glitch Desire
  • 14,632
  • 7
  • 43
  • 55
EEEEE
  • 1