Print out Relative Date / Time from SQL / PHP Datestamp
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?
eg
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
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).
Example:
$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";
// ...
以下是MySQL解决方案的样子:
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
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');
链接地址: http://www.djcxy.com/p/58964.html
上一篇: PHP如何计算相对时间?