我正在尝试创建一个我知道帖子何时创建的东西,然后将 future 4 小时的时间插入我的数据库...
然后我有另一个页面列出所有帖子并显示到期日期的倒计时...
我使用当前时间 (),然后将其与数据库中帖子的到期时间进行比较,得出倒计时中剩余的小时、分钟和秒数。但是我遇到了麻烦...我打开我的电脑查看倒计时,然后在我 friend 的电脑上看到一个完全不同的数字。
服务器时间有什么不同吗?或者什么?
基本上这就是我的数据库中的内容
帖子标题->“我的帖子标题” 时间到期-> 13:50:02
然后我有我的 display_post.php:
while ($allQuestions = mysql_fetch_array($r)){
$now = new DateTime(date("G:i:s",time()));
$exp = new DateTime($allQuestions['time_expires']);
$diff = $now->diff($exp);
printf('%d hours, %d minutes, %d seconds', $diff->h, $diff->i, $diff->s);
}
我不知道这是如何完成的......我也可能在插入一个新帖子时遇到麻烦,这是这里的代码:
$time_created = date("h:i:s",time());
$time_expires = date("h:i:s",time()+(4*3600));
$query = "INSERT into questions (time_created, time_expires)VALUES('".$time_created."', '".$time_expires."')";
mysql_query($query) or die(mysql_error());
那么我将如何着手制作它以便用户可以插入新帖子然后他/她(以及不同时区的其他人)转到该页面以查看还有多少时间到期(自创建后 4 小时) )?
在不同的时区也会影响倒计时中显示的这个数字吗?
最佳答案
您的代码将当前时间加 4 秒
$time_expires = date("h:i:s",time()+4);
如果你需要增加 4 小时那么你的代码必须是这样的:
$time_expires = date("h:i:s",time()+14400);
此外,您需要设置时区,难道您没有收到 php 警告吗?
date_default_timezone_set("UTC"); // is referring to the GMT timing
所以根据 UTC 进行所有计算,一切都应该没问题。
编辑:使用 MYSQL 使您的 php 代码变得简单。
而不是使用这个:
$time_created = date("h:i:s",time());
$time_expires = date("h:i:s",time()+(4*3600));
$query = "INSERT into questions (time_created, time_expires)VALUES('".$time_created."', '".$time_expires."')";
mysql_query($query) or die(mysql_error());
使用这个:
$query = "INSERT into questions (time_created, time_expires)
VALUES(CURTIME(),CURRENT_TIMESTAMP + INTERVAL '4' HOUR)"
mysql_query($query) or die(mysql_error());
另一件事是你与数据库的连接
mysql_connect This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
如果您需要了解更多有关 PDO 的信息,请单击 HERE
关于php - 将到期时间插入数据库并在另一页上倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15194909/