从 mysql 表格式化 PHP time()
-
14-09-2020 - |
题
我正在创建存储在 MySQL 数据库中的评论。
我正在记录 php 时间函数 time()
当评论发布时。这样它就会显示一条消息,例如...“评论...4 秒前发布”,如果我 2 分钟后刷新页面,它会显示“评论...2 分钟前发布”
这是我进入的方式 time()
与其他数据一起存入数据库:
$date=time();
// Insert data into mysql
$sql="INSERT INTO testimonials (username, comment, date)
VALUES ('$username', '$comment', '$date')";
现在...我这样获取数据:
while ($row = mysql_fetch_row($result) )
{
echo "<b>Random Comment</b></br>";
echo ("<p>\n> $row[1]"); //comment
echo ("</br>-$row[0]</p>"); //name
echo ("</br>$row[2]"); //date
我的服务器上的示例输出是:
随机评论
这是有史以来最精彩的评论!!!!
-凯尔
1278905319
如何将时间“1278905319”转换为可读格式,例如“4秒前发布”或处理秒、分钟、小时、天、周、月、年的格式?
PHP 的做法是错误的吗?我读过有关 MySQL 时间戳的内容,但我不明白它或如何让它在我的情况下工作。
所以我的主要问题是,如何将时间格式化为输出时可读的时间。“2秒前”
谢谢。=)
解决方案
这是我找到的一个函数 这里, ,作者是约翰·麦克伦法 (John McClumpha):
<?php
function RelativeTime($timestamp){
$difference = time() - $timestamp;
$periods = array("sec", "min", "hour", "day", "week", "month", "years", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
if ($difference > 0) { // this was in the past
$ending = "ago";
} else { // this was in the future
$difference = -$difference;
$ending = "to go";
}
for($j = 0; $difference >= $lengths[$j]; $j++) $difference /= $lengths[$j];
$difference = round($difference);
if($difference != 1) $periods[$j].= "s";
$text = "$difference $periods[$j] $ending";
return $text;
}
其他提示
首先,让 MySQL 使用自动更新时间戳字段为您插入日期:
CREATE TABLE `table_a` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(255),
`comment` TEXT,
`date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
这样,您无需担心从 PHP 代码插入日期,并且如果您从其他地方(例如,从 MySQL 客户端)进行任何测试,日期仍然会正确插入。
您还应该使用 PHP 日期时间类 (需要 PHP 5.3.0 或更高版本),因为它使日期和时间的处理变得非常简单。下面是从数据库获取一些信息并返回格式化时间间隔的示例:
$result = $mysqli->query(
'SELECT ' .
'`id`, ' .
'`username`, ' .
'`comment`, ' .
'`date`, ' .
'NOW(), ' .
'FROM table');
$row = $result->fetch_assoc();
print_r($row);
Array
(
[id] => 1
[username] = 'Fred'
[comment] = 'My first post'
[date] => 2009-09-28 07:08:12
[now] => 2010-07-12 08:47:03
)
$now = new DateTime($row['now']);
$post = new DateTime($row['date']);
$interval = $post->diff($now);
echo $interval->format('%m months, %d days, %d days, %h hours, %m minutes, %s seconds');
// 9 months, 14 days, 14 days, 1 hours, 9 minutes, 51 seconds
您可以使用以下命令设置间隔格式 日期间隔::格式 参数。通过让 MySQL 返回 NOW()
, ,您可以确保避免应用程序服务器(运行 PHP 的服务器)和数据库服务器之间出现任何时间差异。
不隶属于 StackOverflow