Take the 2-minute tour ×

I have a SQL Datestamp like this: 2012-02-20 21:14:54

How would I print out the relative date and time in PHP?


Occured: a few seconds ago Occured: 4 minutes ago Occured: 4 hours ago Occured: Monday Jan 8th, 2012

After the hours I just want to print out the actual date

share|improve this question
I would recommend you to have a look at Zend Frameworks Zend_Date for parsing dates, and formatting them according to your locale and other requirements –  Vague Feb 20 '12 at 21:25
Hey, that is no so hard to code. Here a sample Just put hands to work. –  NomikOS Feb 20 '12 at 21:30
If comparing between the Database server and your web server I would be careful in case your clocks are inaccurate for whatever reason. Personally I would always compare like with like, so I would compare a datetime from the Database server with a NOW() from the database server just to be certain the same clock is used. –  Simon at mso.net Feb 20 '12 at 21:33
add comment

3 Answers

up vote 2 down vote accepted

Found this after two seconds of Google http://www.mdj.us/web-development/php-programming/another-variation-on-the-time-ago-php-function-use-mysqls-datetime-field-type

In general you chose a unit of time like seconds, test if the time-difference is smaller then the max-value for this unit (60s) and if so, print out "$timeDifference $unit". If not you divide the difference by the units max-value and start over with the next higher unit (minutes).


$timeDif = 60*60*5 + 45; // == 5 hours 45 seconds

// 60 seconds in a minute
if ($timeDif < 60) // false
    return "$timeDif second(s) ago";

// convert seconds to minutes
$timeDif = floor($timeDif / 60); // == 300 = 5 * 60

// 60 minutes in an hour
if ($timeDif < 60) // false
    return "$timeDif minute(s) ago";

// convert minutes to hours
$timeDif = floor($timeDif / 60); // == 5

// 24 hours in a day
if ($timeDif < 24)
    return "$timeDif hour(s) ago";

// ...
share|improve this answer
That link is a 404 page –  Talon Feb 20 '12 at 22:10
Thanks, the script on that page works out sweet. –  Talon Feb 21 '12 at 1:12
add comment

Here's what a MySQL solution might look like:

SELECT date_field, IF (DATEDIFF( NOW(), date_field) < 1, IF ( TIMEDIFF( NOW(), date_field ) < '01:00:00', CONCAT(MINUTE(TIMEDIFF(NOW(), date_field)), ' minutes'), CONCAT(HOUR(TIMEDIFF(NOW(), date_field )), ' hours')), date_field) AS occurred
FROM table
share|improve this answer
add comment

That is no so hard to code. Moreover is quite fun make it. Here a sample, Just put hands to work.
Start converting SQL Datestamp to unixtime like this:

$unixtime = strtotime('2012-02-20 21:14:54');
share|improve this answer
Tested their sample code, it always says "In The Future" Doesn't really work. –  Talon Feb 20 '12 at 22:12
add comment

Your Answer


