views:

84

answers:

3

I want to calculate the difference between two times, one of which is the current time, and the other is just in the format HH:MM, always in the future.

If I just subtract $futuretime from $now, it should, of course, be a positive number.

This works fine until...

If $now is in the afternoon or evening and $futuretime is, say, 7AM next morning, how can I force it to understand the the time is always going to be in the future?

(It's for working out the time of something that occurs about every half an hour during working hours, and then stops until the following morning)

Thanks in advance!

+3  A: 

Simply add a whole day to the difference if it is negative. Assuming that $now and $futuretime are timestamps (stored in seconds since midnight), simply do the following:

$diff = $futuretime - $now;
if ($diff < 0)
    $diff += 24 * 3600;

If they are in HH:MM format:

list($future_hours, $future_mins) = explode(":", $futuretime);
$futuretime = $future_hours * 60 + $future_mins;
list($now_hours, $now_mins) = explode(":", $now);
$now = $now_hours * 60 + $now_mins;
$diff = $futuretime - $now;
if ($diff < 0)
    $diff += 24 * 60;

Of course the latter case returns the difference in minutes, while the former returns the difference in seconds.

Edit: as Andy noted below in the comments, this is not a good solution if you care about changes in DST. See his solution for a better approach.

Tamás
`$diff += 24 * 3600;` this doesn't take daylight saving times into account. E.g. this morning the clock jumped from 02:00 (CET) to 03:00 (CEST).
VolkerK
@Tamás when calculating time and date offsets you must never use homebrew solutions - leap years, daylight savings and other complex calendar inconsistencies are all well catered for by internal PHP functions.
Andy
@Andy indeed, your solution is better if one is using PHP 5.3+. I considered deleting my answer when I realised this, but I thought it's better if I keep it along with your correction so others can see why this is not a good approach. +1 on your solution.
Tamás
+2  A: 

If you're on PHP 5.3+, use PHP's DateTime:

$d1 = new DateTime('14:52:10');
$d2 = new DateTime('12:12:10');

$diff = $d1->diff( $d2 ); 
var_dump( $diff );
Andy
A: 

You can simply convert both dates to timestamp, do the calculations and convert it to required format, i.e. days, hours and minutes. it's quite simple.

Vafello