2

how to get duration between start_date and end_date in hrs min sec format in php?

$start_date=2012-03-23 11:58:14  and $end_date=2012-03-24 11:54:29
Tintu
  • 59
  • 1
  • 3
  • Duplicate http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php – liquorvicar Apr 11 '12 at 06:26

5 Answers5

5

Use DateTime class:

$start_date = new DateTime('2012-03-23 11:58:14');
$end_date = new DateTime('2012-03-24 11:54:29');

$dd = date_diff($end_date, $start_date);

To get hours use $dd->h, minutes - $dd->i, seconds - $dd->s.

echo "Hours = $dd->h, Minutes = $dd->i, Seconds = $dd->s";
s.webbandit
  • 16,332
  • 16
  • 58
  • 82
2

I would

$start_time = strtotime($start_date);
$end_time = strtotime($end_date);
$difference = $end_time - $start_time;
echo date('H:i:s', $difference);

EDIT

I made an error in assuming that the time difference would be less then a day, so if the time difference is greater then a day, you will only see the Hours:minuetes:seconds, which is probably not what you want (if it is ignore this)

So I would now

$seconds = $difference % 60;            //seconds
$difference = floor($difference / 60);
$min = $difference % 60;              // min
$difference = floor($difference / 60);
$hours = $difference;  //hours
echo "$hours : $min : $seconds";

Sorry for the correction

Phil
  • 410
  • 3
  • 12
0

This function will help you

function datediff($interval, $datefrom, $dateto, $using_timestamps = false) {
 /*
  $interval can be:
  yyyy - Number of full years
  q - Number of full quarters
  m - Number of full months
  y - Difference between day numbers
   (eg 1st Jan 2004 is "1", the first day. 2nd Feb 2003 is "33". The datediff is "-32".)
  d - Number of full days
  w - Number of full weekdays
  ww - Number of full weeks
  h - Number of full hours
  n - Number of full minutes
  s - Number of full seconds (default)
 */

http://php.net/manual/en/function.date-diff.php

0
  1. format those string to date
  2. transform those date to milliseconds
  3. do endate - stardate
  4. from the result calculate the h:mm:ss
storm_buster
  • 7,362
  • 18
  • 53
  • 75
0

See it working here: http://codepad.viper-7.com/FPuOks

$start_date="2012-03-22 11:58:14";
$end_date="2012-03-24 11:54:29";

$start_time = strtotime($start_date);
$end_time = strtotime($end_date);
$difference = $end_time - $start_time;

echo sprintf("%02d%s%02d%s%02d", floor($difference/3600), ':', ($difference/60)%60, ':', $difference%60); // outputs 47:56:15
Gert Van de Ven
  • 997
  • 6
  • 6