1

我和我的朋友正在为 IRC Bot 编写一个相当基本的正常运行时间脚本。

这是我们的代码:

function Uptime()
{
    global $uptimeStart;
    $currentTime = time();
    $uptime = $currentTime - $uptimeStart;
    $this->sendIRC("PRIVMSG {$this->ircChannel} :Uptime: ".date("z",$uptime)." Day(s) - ".date("H:i:s",$uptime));
}

$uptimeStart 在脚本运行时立即设置,如 time();

出于某种原因,当我执行此功能时,它从 364 天 19 小时开始。我不知道为什么。

4

4 回答 4

4

$uptime不是应该在 中使用的时间戳date(),而是时间差。您在那里有一定的秒数,而不是时间戳(与实际日期相对应。

只需使用这样的东西来计算(快速的,在 1 天、2 小时等方面投入一些额外的大脑);)

 $minutes = $uptime / 60;
 $hours   = $minuts/60 ;
 $days    = $hours / 24

ETC

于 2011-01-23T15:06:28.413 回答
2

如果您有 5.3 或更高版本,请使用 DateTime 和 DateInterval 类:

$uptimeStart = new DateTime(); //at the beginning of your script

function Uptime() {
  global $uptimeStart;
  $end = new DateTime();

  $diff = $uptimeStart->diff($end);

  return $diff->format("%a days %H:%i:%s");
}
于 2011-01-23T15:09:31.083 回答
1

通过调用那个时差,你不会得到任何有意义的东西date()。您应该利用该时间差并逐步除以年、月、日、小时,所有这些都以秒为单位。这样你就会得到这些术语的时差。

$daySeconds = 86400 ;
$monthSeconds = 86400 * 30 ;
$yearSeconds = 86400 * 365 ;

$years = $uptime / $yearSeconds ;
$yearsRemaining = $uptime % $yearSeconds ;

$months = $yearsRemaining / $monthSeconds ;
$monthsRemaining = $yearsRemaining % $monthSeconds ;

$days = $monthsRemaining / $daySeconds ;

..等以获得小时和分钟。

于 2011-01-23T15:09:20.037 回答
0

第二个参数设置为 0 的 date() 函数实际上会返回您(零日期 +(您的时区)),其中“零日期”是“00:00:00 1970-01-01”。看起来您的时区是 UTC-5,所以您得到 (365 天 24 小时) - (5 小时) = (364 天 19 小时)

此外,date() 函数不是显示两个日期之间差异的最佳方式。查看其他答案 - 已经发布了计算年份差异的好方法

于 2011-01-23T15:17:11.293 回答