0

我在名为 created_at 的数据库中有一个字段,并以这种格式存储数据:

1980-11-28 04:05:25

所以我想知道自该日期以来已经过去了多少时间,例如:3秒|| 5 分钟 || 22 小时 || 1 天 || 6 周 || 1 个月 || 3 年(注意 || 所以可以是任何选项,而不是全部)。我不知道我是否可以直接从使用 SQL 语言的查询含义中得到这个,我检查了这个 [1] 但找不到正确的函数来执行此操作。所以我想用 PHP 得到它,但要么不知道怎么做。有什么可以帮助我的吗?

[1] http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html

4

1 回答 1

1

I'm unsure if there is a native PHP function that allows you to do this, however you can make one. I found this one at http://css-tricks.com/snippets/php/time-ago-function/ and edited it to make it a bit more functional. Using this we can just simply put your created_at string through it and get the result.

// The function to get the final string
function timeago($tm,$lim=0) {
   $cur_tm = time(); $dif = $cur_tm-$tm;
   $pds = array('second','minute','hour','day','week','month','year','decade');
   $lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
   for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);
   $no = floor($no); if($no <> 1) $pds[$v] .='s'; $x=sprintf("%d %s",$no,$pds[$v]);
   if($lim>1 && ($v >= 1)&&(($cur_tm-$_tm) > 0)) $x .= ', ' . timeago($_tm,$lim-1); else $x .= ' ago';
   return $x;
}

// Run the MySQL query to get the string
$query = mysql_query("SELECT `created_at` FROM `table` LIMIT 1");
// Put the string into a PHP variable
$created_at = mysql_result($query,0);

// Show the results
echo timeago($created_at);
// This will output something like  '4 years ago' or '12 seconds ago'

// You can fine tune how accurate you want the function to make your 'time ago' string to be by adding a number as the second variable for the function
// For example:
echo timeago($created_at, 6);
// This will output something like '4 decades, 2 years, 7 months, 1 week, 15 hours, 49 minutes, 12 seconds ago'
于 2012-08-15T15:13:41.810 回答