tags:

views:

808

answers:

3

So, I have a field in my users table named last_active which updates every time a user reloads a page.
It's stored in unix timestamp.

I would like to output it like this: Last online: 4 d 18 h 19 m ago

How would one do that? Can you do it with php's date()?

Thank you.

+2  A: 

The simplest approach to this is to take the last_active timestamp, and the current timestamp with time(). Then subtract the last active from the current timestamp, and then you simply divide the result with the amount of seconds in a day to get difference in days, amount of seconds in an hour to get difference in hours and so on.

This approach may be slightly inaccurate in some special cases (leap years, etc.) but it should suffice for your simpler usecase

Jani Hartikainen
Unix timestamps is basicly amount of seconds after january 1st, 1970.If you substract current timestamp from any timestamp in the past, you will get the exact seconds between these 2 stamps and its only matter of converting the seconds to days/hours/mins after that. Leap year isnt causing any sideeffects on this.
rasjani
Yeah I was probably a bit unclear. In this case it will not cause any side effects, but if you try getting exact dates with timestamp style second calculations you may run into problems. Thanks for pointing it out though
Jani Hartikainen
+3  A: 

You could achieve this directly in MySQL if you like:

select date_format(from_unixtime(current_timestamp - last_timestamp), 
    'Last online: %e days, %k hours, %i minutes, %s seconds ago.');

(current_timestamp can be replaced with unix_timestamp(now()) if you want it calculated in-place)

DATE_FORMAT allows you to have a custom string based on a specific date. If you populate its date with the difference between two timestamps, it will work as you've asked.

The above solution will only work if it's under a month; if you want days of the year, use %j. The documentation for the function shows more.

Jeremy Smyth
Reasonable, but will display redundant information, e.g. 0 days, if the time is less than one day away
David Caunt
A: 

Check out this article, it's exactly what you need

http://blog.fedecarg.com/2009/06/25/format-a-time-interval-with-the-requested-granularity/

David Caunt