0

私はcreated_atという名前のDBにフィールドを持っており、次の形式でデータを保存します。

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

これを可能にするネイティブPHP関数があるかどうかはわかりませんが、作成することはできます。これはhttp://css-tricks.com/snippets/php/time-ago-function/で見つけて、もう少し機能的にするように編集しました。これを使用すると、文字列を単純にcreated_at通過させて結果を得ることができます。

// 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 に答える