Jump to content

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


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);

$time1 = time();
$time2 = time() + 328523;   /* some random number */

$dSecs = abs($time2 - $time1);
$dHours = $dSecs / pow(60, 2);

Something like that, there is probably a PHP function to do this...

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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