我有一个包含2个日期列的表,一个是时间戳值(例如1359380165),另一个是正常日期时间值(例如2013-01-28 08:32:53)。
我想找到现在(当前)和上面列出的这些日期之间的时间间隔。所以结果将是例如。
有什么想法吗?
答案 0 :(得分:2)
这个函数应该做类似于你所做的事情,试一试,它只需要像你的'1359380165那样传递给它的unix时间戳。
function getRelativeTime($timestamp)
{
$timeDifference = time() - $timestamp;
$timePeriods = array('second', 'minute', 'hour', 'day', 'week','month', 'years', 'decade');
$timeLengths = array('60', '60', '24', '7', '4.35', '12', '10');
if ($timeDifference > 0)
{
$timeSuffix = 'ago';
}
else
{
$timeDifference = -$timeDifference;
$timeSuffix = 'to go';
}
for($i = 0; $timeDifference >= $timeLengths[$i]; $i++)
{
$timeDifference/= $timeLengths[$i];
$timeDifference = round($timeDifference);
}
if($timeDifference != 1) $timePeriods[$i].= 's';
return $timeDifference . ' ' . $timePeriods[$i] . ' ' . $timeSuffix;
}
答案 1 :(得分:0)
假设有这样一个表:
id int unsigned not null auto_increment primary key
username varchar(45) not null
utime int
dtime timestamp
为什么不构造查询以便PHP以相同的格式接收两个时间戳?像这样:
SELECT id, username, FROM_UNIXTIME(utime, '%Y-%m-%d %H.%i.%s') AS ut, dtime AS dt FROM mytable;
或
SELECT id, username, utime AS ut, UNIX_TIMESTAMP(dtime) as dt FROM mytable;
然后你可以用同样的方式处理ut和dt。
有一个很好的相对时间函数here。它需要一个unix时间戳。