ParisNakitaKejser
ParisNakitaKejser

Reputation: 14949

Determining elapsed time

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

Upvotes: 1

Views: 316

Answers (5)

Sadat
Sadat

Reputation: 3481

$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);
echo $time_diff;

Upvotes: 0

dnagirl
dnagirl

Reputation: 20446

$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.

Upvotes: 0

yoda
yoda

Reputation: 10981

Use php timestamp for the job :

echo date("H:i:s", ($end_timestamp - $start_timestamp));

Upvotes: 0

Pascal MARTIN
Pascal MARTIN

Reputation: 401172

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...

Upvotes: 3

fbrereto
fbrereto

Reputation: 35935

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.

Upvotes: 1

Related Questions