您好,我有一对夫妇在我的MySQL数据库服务器的帖子,每个帖子的内容信息的一个格式的日期和时间日期时间(例2010-11-26 21点55分09秒)在发表的时候.
因此,我想从具有函数NOW()的SQL服务器中检索实际日期和时间,并计算发布信息的秒数或分钟数或小时数或天数.
我不知道如何创建这个PHP脚本,但我知道肯定已经完成,所以感谢任何帮助.
你可以使用date_diff()函数
http://php.net/manual/en/function.date-diff.php
就像是...
<?php
$now = time();
$then = $posttime;
$diff = date_diff($now,$then);
echo $diff->format('%R%d days'); #change format for different timescales
?>
Run Code Online (Sandbox Code Playgroud)
编辑 -
我实际上使用此功能在我的一个Twitter应用程序上解决了这个问题...
function time_since ( $start )
{
$end = time();
$diff = $end - $start;
$days = floor ( $diff/86400 ); //calculate the days
$diff = $diff - ($days*86400); // subtract the days
$hours = floor ( $diff/3600 ); // calculate the hours
$diff = $diff - ($hours*3600); // subtract the hours
$mins = floor ( $diff/60 ); // calculate the minutes
$diff = $diff - ($mins*60); // subtract the mins
$secs = $diff; // what's left is the seconds;
if ($secs!=0)
{
$secs .= " seconds";
if ($secs=="1 seconds") $secs = "1 second";
}
else $secs = '';
if ($mins!=0)
{
$mins .= " mins ";
if ($mins=="1 mins ") $mins = "1 min ";
$secs = '';
}
else $mins = '';
if ($hours!=0)
{
$hours .= " hours ";
if ($hours=="1 hours ") $hours = "1 hour ";
$secs = '';
}
else $hours = '';
if ($days!=0)
{
$days .= " days ";
if ($days=="1 days ") $days = "1 day ";
$mins = '';
$secs = '';
if ($days == "-1 days ") {
$days = $hours = $mins = '';
$secs = "less than 10 seconds";
}
}
else $days = '';
return "$days $hours $mins $secs ago";
}
Run Code Online (Sandbox Code Playgroud)
您在检查时间的unix时间戳(传递时间)中传递它,并返回各种字符串.
正如billythekid所说,date_diff()如果您使用的是PHP5.3+,则可以使用该功能,如果您不是,则有多种方法。正如其他海报所示。如果您想知道按“小时:分钟:秒”层次结构划分的时间,MySQL 中最快的方法是使用TIMEDIFF() 函数。
SELECT TIMEDIFF(NOW(), '2010-11-26 12:00:00');
Run Code Online (Sandbox Code Playgroud)
如果您想要以秒为单位,请使用 MySQL 或 PHP 中的 unix 时间戳功能,您可以使用strtotime().