John
John

Reputation: 13

Trouble getting age in hours

I am trying to calculate the age of something in hours.

$data['record'] is a mysql NOW() timestamp in a DATETIME field.

$data['record'] is 20 minutes old, when I do :

$minutes= date('i',(strtotime("now")-strtotime($data['record'])));

$minutes returns 20 properly, however for some reason when I try $hours it returns '5'.

$hours = date('g',(strtotime("now")-strtotime($data['record'])));

This does not make sense, as $hours should be returning 0 as the record is less than 60 minutes old...

When I checked the value of "strtotime("now")-strtotime($data['record'])" it is equal to '980'. Help!

Upvotes: 0

Views: 224

Answers (3)

Wipqozn
Wipqozn

Reputation: 1314

Please See: http://php.net/manual/en/function.date.php

When the $format parameter="g", it returns a value 1-12.

Upvotes: 1

shmeeps
shmeeps

Reputation: 7853

Date will not quite work like you're expecting it to.

Date takes a time stamp (# of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)), and converts that into a legible time format. Essentially, with a value of 980, you are going to get January First at midnight + 980 seconds (roughly January 1 1970 00:16:20 GMT. When you convert for the time zone difference, (chances are, about 5 hours difference) that's how you get five.

To fix this, simply take 980, and divide by 60 to get minutes, then divide by 60 again to get hours, so:

$hours = ((strtotime("now")-strtotime($data['record'])) / 60) / 60;

There's no need for date, as you need a relative time, not an absolute time.

Upvotes: 0

Femaref
Femaref

Reputation: 61467

Please compare the output of strtotime("now") of php and select now(); in sql. I think there is a timezone problem hidden here.

As you said, strtotime("now")-strtotime($data['record']) returns 980, which should be in minutes. 960 is divideable by 60 and comes out at 16 hours, so 980 is 16 hours 20 minutes - the 20 minutes are exactly what you are looking for. You'll need to adjust either instance to use the time of the other - I would go with always using UTC. If you need to display it, parse it appropiately and output the local time.

Upvotes: 2

Related Questions