【问题标题】:How to return the amount of years passed?如何返回过去的年数?
【发布时间】:2011-01-23 14:57:35
【问题描述】:

我和我的朋友正在为 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 小时开始。我不知道为什么。

【问题讨论】:

  • 1.为什么不将变量作为函数参数传递 2.var_dump($currentTime, $uptimeStart) 3. 要计算差异,请使用简单的数学,而不是 date()

标签: php date time uptime


【解决方案1】:

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

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

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

【讨论】:

    【解决方案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");
    }
    

    【讨论】:

      【解决方案3】:

      在那个时差上调用date() 不会有任何意义。您应该利用该时间差并逐步除以年、月、日、小时,所有这些都以秒为单位。这样您就可以知道这些术语的时差。

      $daySeconds = 86400 ;
      $monthSeconds = 86400 * 30 ;
      $yearSeconds = 86400 * 365 ;
      
      $years = $uptime / $yearSeconds ;
      $yearsRemaining = $uptime % $yearSeconds ;
      
      $months = $yearsRemaining / $monthSeconds ;
      $monthsRemaining = $yearsRemaining % $monthSeconds ;
      
      $days = $monthsRemaining / $daySeconds ;
      

      .. 等获取小时和分钟。

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-20
          • 1970-01-01
          • 1970-01-01
          • 2022-09-26
          • 1970-01-01
          相关资源
          最近更新 更多