我目前正在制作一个帖子评论系统。
当用户评论一篇文章时,我想将日期和时间存储在数据库中。现有的注释应该显示自添加注释以来已经过了多长时间的时间差。
Ie。2分钟前,3天前,等等——类似于Facebook上的情况。
是否有任何方法或属性在SQL或PHP来处理这个?
哪种SQL数据类型适合此目的?日期时间还是时间戳?
MySQL中的时间戳通常用于跟踪记录的更改,并且通常在每次记录更改时更新。如果您想要存储一个特定的值,您应该使用datetime字段。如果您想要在使用UNIX时间戳或本地MySQL datetime字段之间做出选择,请使用本地格式。你可以用这种方式在MySQL中进行计算("SELECT DATE_ADD(my_datetime, INTERVAL 1 DAY)"),当你查询记录时,如果你想用PHP操作它,很容易将值的格式更改为UNIX时间戳("SELECT UNIX_TIMESTAMP(my_datetime)")。一个重要的区别是DATETIME表示日期(在日历中)和时间(可以在挂钟上观察到),而TIMESTAMP表示一个定义良好的时间点。如果您的应用程序处理时区,这可能非常重要。"2010-09-01 16:31:00"是多久以前的事了?这取决于你所在的时区。对我来说,这只是几秒钟前,对你来说,这可能代表着未来的一个时间。如果我说1283351460秒since '1970-01-01 00:00:00 UTC',你就知道我说的是哪个时间点了。
$timeFirst = strtotime($postDateTime);
$timeSecond = strtotime($commentDateTime);
$differenceInSeconds = $timeSecond - $timeFirst;
显示时间:
function relativedate($secs) {
$second = 1;
$minute = 60;
$hour = 60*60;
$day = 60*60*24;
$week = 60*60*24*7;
$month = 60*60*24*7*30;
$year = 60*60*24*7*30*365;
if ($secs <= 0) { $output = "now";
}elseif ($secs > $second && $secs < $minute) { $output = round($secs/$second)." second";
}elseif ($secs >= $minute && $secs < $hour) { $output = round($secs/$minute)." minute";
}elseif ($secs >= $hour && $secs < $day) { $output = round($secs/$hour)." hour";
}elseif ($secs >= $day && $secs < $week) { $output = round($secs/$day)." day";
}elseif ($secs >= $week && $secs < $month) { $output = round($secs/$week)." week";
}elseif ($secs >= $month && $secs < $year) { $output = round($secs/$month)." month";
}elseif ($secs >= $year && $secs < $year*10) { $output = round($secs/$year)." year";
}else{ $output = " more than a decade ago"; }
if ($output <> "now"){
$output = (substr($output,0,2)<>"1 ") ? $output."s" : $output;
}
return $output;
}
echo relativedate(60); // 1 minute
它将完全像正面一样显示。您必须以秒为单位将评论和帖子之间的差异传递给函数。
我只是想改进小君的回答。在我尝试在我的代码上实现这个之后,Jun的代码有一点不正确的计算,在月和年计算
这是我的代码
function relativedate($secs) {
$second = 1;
$minute = 60;
$hour = 60*60;
$day = 60*60*24;
$week = 60*60*24*7;
$month = 60*60*24*7*4; // because 1 month is 4 week
$year = 60*60*24*7*4*12; // because 1 year is 12 month
if ($secs <= 0) { $output = "now";
}elseif ($secs > $second && $secs < $minute) { $output = round($secs/$second)." second";
}elseif ($secs >= $minute && $secs < $hour) { $output = round($secs/$minute)." minute";
}elseif ($secs >= $hour && $secs < $day) { $output = round($secs/$hour)." hour";
}elseif ($secs >= $day && $secs < $week) { $output = round($secs/$day)." day";
}elseif ($secs >= $week && $secs < $month) { $output = round($secs/$week)." week";
}elseif ($secs >= $month && $secs < $year) { $output = round($secs/$month)." month";
}elseif ($secs >= $year && $secs < $year*10) { $output = round($secs/$year)." year";
}else{ $output = " more than a decade ago"; }
if ($output <> "now"){
$output = (substr($output,0,2)<>"1 ") ? $output."s" : $output;
}
return $output;
}
echo relativedate(60); // 1 minute