我正在尝试让PHP向我展示一些timeago功能。我正在遍历Mysql表的结果,该表中有一个名为“ aplicationdate”的列名,数据库中的格式为“ Ymd”。但这只是向我显示了一些负的大数字,如-16328。这是我的timeago filev任何帮助将不胜感激:
<? php
function timeAgo($time_ago) {
$cur_time = date('Y-m-d');
$time_elapsed = $cur_time - $time_ago;
$days = round($time_elapsed / 86400);
$weeks = round($time_elapsed / 604800);
$months = round($time_elapsed / 2600640);
$years = round($time_elapsed / 31207680);
//Days
if ($days <= 7) {
if ($days == 1) {
echo "yesterday";
} else {
echo "$days days ago";
}
}
//Weeks
else if ($weeks <= 4.3) {
if ($weeks == 1) {
echo "a week ago";
} else {
echo "$weeks weeks ago";
}
}
//Months
else if ($months <= 12) {
if ($months == 1) {
echo "a month ago";
} else {
echo "$months months ago";
}
}
//Years
else {
if ($years == 1) {
echo "one year ago";
} else {
echo "$years years ago";
}
}
}
?>
这是在另一个名为profile.php的文件中实现的方式,timeago文件包含在此文件中
<? php
$mysqli = new mysqli("localhost", "root", "", "cx");
/* check connection */
if ($mysqli - > connect_errno) {
printf("Connect failed: %s\n", $mysqli - > connect_error);
exit();
}
$idced_history = $_GET['idced'];
$query = "SELECT * FROM applications WHERE idced='$idced_history'";
if ($result = $mysqli - > query($query)) {
while ($row = $result - > fetch_assoc()) {
$curenttime = $row["applicationdate"];
$time_ago = strtotime($curenttime);
echo "<br><b>Applied On:</b> ".$row["applicationdate"]." ".timeAgo($time_ago)." <br>";
}
$result - > free();
}
$mysqli - > close();
?>
最佳答案
$cur_time
是字符串,而不是数字。看来您需要在使用它之前将其转换为Unix时间戳。因此,请使用time()
代替date()
:
$cur_time = time();
(这假设
$time_ago
也是Unix时间戳记)