我正在开发一个浏览器游戏,当玩家的健康状况变为0时,他会住院30分钟。我正在使用strtotime来检查离开医院还有多少时间。
<?php
$current_time = strtotime('now') + 1800; // This variable goes to the database
// The player gets hospitalized for 30 minutes, that's 1800 seconds.
// Updating the database ...
$sql = "UPDATE playerstats SET hospitalized='1', hospitaltimer=$current_time WHERE id = $id";
?>
现在让我们说玩家在页面上说他必须等待??分钟 ??直到他出院。
<?php
// Getting the timer from the database ...
global $db;
$sql = "SELECT * FROM playerstats WHERE id=$id";
$stmt = $db->query($sql);
$result = $stmt->fetchAll();
$timer = $result[0]['hospitaltimer'];
// substracting strtotime('now') from the timer to see how many seconds are left
// until the player is released from the hospital
$timer = $timer - strtotime('now');
// Lets just say that 2 minutes have passed, the $timer should now be with a result
// like 1680 or something,
?>
我的问题是,如何将计时器分为分钟和几秒?我想将剩下的1680秒拆分为分钟和秒。还是谢谢你。
答案 0 :(得分:0)
由于您将hospitaltimer
存储为距Unix纪元的秒数,因此减去两个strtotime
数字将转换为日期,例如,距Unix纪元1680秒。不是您要找的东西。
我建议通过以yyyy-mm-dd格式存储“退出时间”来解决此问题
a。-您需要更改表并将hospitaltimer
转换为DATETIME
字段。这很简单
b.-更改代码,将hospitaltimer
值存储为yyyy-mm-dd hh:mm:ss,如下所示:
$current_time = date('Y-m-d H:i:s', strtotime('now') + 1800); // This variable goes to the database
,然后更改逻辑以显示剩余时间:
$timer = date_create($result[0]['hospitaltimer']); // the "exit time" you inserted
$now = date_create(date('Y-m-d H:i:s'));
$diff = date_diff($timer,$now)->format('%r%i minutes %s seconds');
if ($diff < 0)
{
echo "out";
}
else
{
echo $diff." before being able to leave";
}
或者,减去不同的strtotime()
操作的输出将是一种非标准的计算日期的方式,您可以通过以下方式解决该问题:
$timer = $timer - strtotime('now');
// now the timer reads 1680 per your example
$seconds = $timer % 60; // use modulo 60 to calculate seconds remaining after dividing seconds by 60 and retrieving the integer part of the result
$minutes = ($timer - $seconds) / 60; // from full timer, substract the seconds and the remaining amount, divided by 60 is converted to minutes
这两种方法都可以使用,但是将hospitaltimer
存储为时间戳的好处是,在任何给定时间点,您都可以轻松查询该表,以找出有多少用户仍在住院(例如)只需使用where hospitaltimer > now()