tags:

views:

69

answers:

5

I need to somehow take a unix timestamp and output it like below

Can this be done with MySQL? Or php

Mike                             7s ago
Jim                              44s ago
John                             59s ago
Amanda                           1m ago
Ryan                             1m ago
Sarah                            1m ago
Tom                              2m ago
Pamela                           2m ago
Ruben                            3m ago
Pamela                           5h ago

As you can guess i only wanna print the minute, not minutes and seconds(1m 3s ago)

What should I look into?

A: 

PHP's date() function

as well as time() and some others that are linked in those docs

This can also be done in Mysql with date and time functions

Viper_Sb
A: 

You can try my Timeago suggestion here.

It can give outputs like this:

You opened this page less than a minute ago. (This will update every minute. Wait for it.)

This page was last modified 11 days ago.

Ryan was born 31 years ago.

Bakkal
+3  A: 

PHP 5.3 and newer have DateTime objects that you can construct with data coming back from a database. These DateTime objects have a diff method to get the difference between two dates as a DateInterval object, which you can then format.

Edit: corrected sub to diff.

Edit 2: Two catches with doing it this way:

  1. DateTime's constructor doesn't appear to take a UNIX timestamp... unless prefixed with an @, like this: $startDate = new DateTime('@' . $timestamp);
  2. You won't know what the largest unit is without manually checking them. To get an individual field, you still need to use format, but with just a single code... Something like $years = $dateDiff->format('y');
R. Bemrose
+1 if you're new to PHP date handling, use `DateTime` from the start. It's way better than timestamps.
Pekka
I made a mistake and used sub instead of diff. I've fixed it now.
R. Bemrose
+1  A: 

Yes it can be done. See related post

$before // this is a UNIX timestamp from some time in the past, maybe loaded from mysql
$now = time()

$diff = $now - $before;
if( 1 > $diff ){
   exit('Target Event Already Passed (or is passing this very instant)');
} else {
   $w = $diff / 86400 / 7;
   $d = $diff / 86400 % 7;
   $h = $diff / 3600 % 24;
   $m = $diff / 60 % 60; 
   $s = $diff % 60;

   return "{$w} weeks, {$d} days, {$h} hours, {$m} minutes and {$s} secs away!"
}
Tim
A: 

I dont have a mysql server at hand, but a combination of the following commands should get you something like what you want.

DATEDIFF

AND

DATEFORMAT

Toby Allen