使用 php time() 计算剩余时间

calculating time remaining using php time()

我有一个 php 脚本,我需要确保没有超过预设的 "future" 时间。

当最初记录时间(或过去并需要重新记录)时,我正在采取:

$newTime = time() + 15000; // 2.5 minutes from "now"

系统在数据库中抛出这个没问题,数字似乎是正确的。

现在,加载页面时,它会从数据库中提取数字并将其加载到 .php 文件中:

error_reporting(E_ALL);
ini_set('display_errors',1);
$tname = $_SESSION['username']."Data";
$results = $conn->query("SELECT val FROM $tname where pri='pettyTimer'") or die(mysqli_error($conn)); 
  //$conn declared elsewhere for connection and does work properly
$row = $results->fetch_assoc();
$timer = $row['val'];

然后我在比较时间:

$now = time();
if ($timer > time()) { //script below
} else {
//more script that seems to be working fine
}

当原始条件 $timer > time() 为真时,我试图分解剩余时间的分钟和秒数,并以用户可读的基本格式回应它们:

$raw = ($timer - $now);
$minutesLeft = floor($raw / 60000);
$totalMinutes2Mils = $minutesLeft * 60000;
$totalRemainingSecs = round(($raw - $totalMinutes2Mils) / (1000));

echo "You are still laying low from the last job you ran. You still have ".$minutesLeft." Minutes and ".$totalRemainingSecs." Seconds left.";

我的问题是,当我 refresh/reload 页面时,时间似乎没有变化。

我回显了 time()$timer,当我第一次加载它时它们相隔 15000 毫秒,所以这应该只存在(条件为真)大约 2.5 分钟,但我已经自从我上一次设置后至少工作了 5 分钟,现在仍然是 14 秒。

有人可以仔细检查我的数学以确保我计算正确吗?谢谢!

time() 函数 returns 当前时间,自 Unix 纪元(1970 年 1 月 1 日 00:00:00 GMT)以来的秒数。

http://www.w3schools.com/php/func_date_time.asp

您将其视为毫秒,但应将​​其视为直接秒。大约 /1000,你应该没问题。

$minutesLeft = floor($raw / 60);
$totalMinutes2Mils = $minutesLeft * 60;

$newTime = time() + (60*2.5); // 2.5 minutes from "now"

time() returns 秒,而不是毫秒,因此您应该添加 150 而不是 15000 以获得 2:30 分钟。