Page 1 of 1

Calculate Hours & Minutes between two Dates/Time

Posted: Wed Dec 23, 2009 6:40 pm
by julzk
Hi,

I am wanting to Calculate Hours & Minutes between two Dates/Time.

I have four fields: ss_datestart, ss_dateend and ss_timestart and ss_timeend.

I want to display the hours and minutes between two dates/times.

Example:

$ss_datestart $ss_timestart --- $ss_dateend $ss_timeend
05-12-2009 13:44:31 --- 05-12-2009 17:55:31

I want it to then display the difference in hours and minutes only, so it would return: 04h 11m (ignoring the seconds of course).


And if it were something that went over a day so:

05-12-2009 13:44:31 --- 06-12-2009 17:55:31 <--- This would return: 28h 11m


FYI: Dates are dd-mm-yyyy

Re: Calculate Hours & Minutes between two Dates/Time

Posted: Wed Dec 23, 2009 7:47 pm
by requinix
One more reason to switch to PHP 5.3...

Code: Select all

$date1 = "2009-10-26"; $time1 = "02:30:00";
$date2 = "2009-11-02"; $time2 = "02:30:00";
 
$before = strtotime($date1 . " " . $time1);
$after = strtotime($date2 . " " . $time2);
$diff = $after - $before;
//$diff += 3600 * (date("I", $after) - date("I", $before)); // daylight savings adjustments
 
// $diff is in seconds
$hours = floor($diff / 3600);
$minutes = floor(($diff - $hours * 3600) / 60);
$seconds = $diff - $hours * 3600 - $minutes * 60;
 
printf("It was %02uh %02um %02us between %s %s and %s %s<br>\n", $hours, $minutes, $seconds, $date1, $time1, $date2, $time2);
That one line about daylight savings is to adjust for what people think should be the correct time (they're wrong).

Re: Calculate Hours & Minutes between two Dates/Time

Posted: Wed Dec 23, 2009 7:59 pm
by manohoo
Try this

Code: Select all

 
<?php
 
//mktime(hour,minute,second,month,day,year,is_dst) 
$start = mktime(13,44,31,12,5,2009);
$end = mktime(17,55,31,12,6,2009);
 
// the difference in seconds
$diffSeconds = $end - $start;
 
// the difference in hours and minutes
$hrs = (int) ($diffSeconds / 3600);
$mins = (int) (($diffSeconds % 3600) / 60)
 
echo "$hrs:$mins" ;
?>
 
Or, if you wanted seconds as well:

Code: Select all

 
<?php
 
//mktime(hour,minute,second,month,day,year,is_dst) 
$start = mktime(13,44,31,12,5,2009);
$end = mktime(17,55,31,12,6,2009);
 
// the difference in seconds
$diffSeconds = $end - $start;
 
// the difference in hours and seconds
$hrs = (int) ($diffSeconds / 3600);
$mins = (int) (($diffSeconds % 3600) / 60);
$secs =  $diffSeconds - ($hrs *3600 + $mins * 60);
 
echo "$hrs:$mins:$secs" ;