tags:

views:

95

answers:

5

I have two times in PHP and I would like to determine the elapsed hours and minutes. For instance:

8:30 to 10:00 would be 1:30

+1  A: 

You can use the answer to this question to convert your times to integer values, then do the subtraction. From there you'll want to convert that result to units-hours-minutes, but that shouldn't be too hard.

fbrereto
...and then undo the conversion from the linked answer. You need to be careful about 12-hour time (AM/PM) vs 24-hour time.
Matt Ball
and daylight savings time changeover days. Have a look at the DateTime class. It deals with all that.
dnagirl
+3  A: 

A solution might be to use strtotime to convert your dates/times to timestamps :

$first_str = '8:30';
$first_ts = strtotime($first_str);

$second_str = '10:00';
$second_ts = strtotime($second_str);

And, then, do the difference :

$difference_seconds = abs($second_ts - $first_ts);

And get the result in minutes or hours :

$difference_minutes = $difference_seconds / 60;
$difference_hours = $difference_minutes / 60;
var_dump($difference_minutes, $difference_hours);

You'll get :

int 90
float 1.5

What you now have to find out is how to display that ;-)


(edit after thinking a bit more)

A possibility to display the difference might be using the date function ; something like this should do :

date_default_timezone_set('UTC');

$date = date('H:i', $difference_seconds);
var_dump($date);

And I'm getting :

string '01:30' (length=5)

Note that, on my system, I had to use date_default_timezone_set to set the timezone to UTC -- else, I was getting "02:30", instead of "01:30" -- probably because I'm in France, and FR is the locale of my system...

Pascal MARTIN
+1, for almost exactly what I was about to post...grr... =P
David Thomas
hmmm its not working, if start clock is 4:11 and end clock is 20:13 my code says 17:02 amd that not ture, its to by 16:02, what mattere here :/
NeoNmaN
@NeoNmaN : did you try calling date_default_timezone_set ? When I'm not using it, I'm getting 17:02 too -- but when using it, I'm getting 16:02
Pascal MARTIN
A: 

Hi,

Use php timestamp for the job :

echo date("H:i:s", ($end_timestamp - $start_timestamp));
yoda
A: 
$time1='08:30';
$time2='10:00';
list($h1,$m1) = explode($time1);
list($h2,$m2) = explode($time2);
$time_diff = abs(($h1*60+$m1)-($h2*60+$m2));
$time_diff = floor($time_diff/60).':'.floor($time_diff%60);
Sadat
A: 
$d1=date_create()->setTime(8, 30);
$d2=date_create()->setTime(10, 00);
echo $d1->diff($d2)->format("%H:%i:%s");

The above uses the new(ish) DateTime and DateInterval classes. The major advantages of these classes are that dates outside the Unix epoch are no longer a problem and daylight savings time, leap years and various other time oddities are handled.

dnagirl