Jump to content

[SOLVED] Help with finding difference in hours between two times?


kernelgpf

Recommended Posts

I recently switched this code to subtract days to hours, but it isn't working.. it's coming out with "343957987" hours and crazy stuff like that.

 

Here's my code-

 

$expirationdate[0] = $row3[datetillcompletion];
$startdate[0] = date("l, M dS (h:i a) ");

$startdate = strtotime($startdate[0]);
$expirationdate = strtotime($expirationdate[0]);
$delta = $expirationdate - $startdate;

$final=round($delta/3600);

Just for example, so the times were different ;)

 

Can chuck it in a function for a one liner,

function diffHours($a, $b)
{
    return (abs($a - $b) / pow(60, 2));
}

 

abs() because we only care about the difference in scalar terms.

$hours = diffHours($row['datetillcompletion'], time());

Returns the amount of hours between the 'datetillcompletion' and the current time.

 

Note: It really helps if you understand unix timestamps, no need to convert it to a string, then back to a timestamp.

I don't understand unix timestamps.. I'll have to look at that when I get a chance. I tried your code, and the result I got was "331009.52944444"... I can round it, but the timestamp in the DB for "$row[datetillcompletion]" is "2007-10-06 10:00:00"... that isn't right. Any other suggestions?

diffHours() will tell you the difference between 2 unix timestamps, in hours.

 

A unix timestamp is how many seconds have past since the UNIX EPOCH (1970), once you realize that it's pretty easy. You should be storing the timestamp in the database, not a string.

Nothing really to fix it,

 

$hours = diffHours(strtotime($row3['datetillcompletion']), time());

 

Does that work? you just need to pass 2 timestamps to diffHours. strtotime() converts a string to a timestamp.

 

You should consider changing your database so dates/times are stored as unix timestamps, you can get the current time with time().

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.