【问题标题】:How to convert time interval into seconds in PHP如何在PHP中将时间间隔转换为秒
【发布时间】:2021-04-05 08:19:21
【问题描述】:

我有两个日期,我需要知道它们之间的时差是否不超过 72 小时。包括秒数

阅读 PHP 文档我发现 date_diff() 是解决此问题的方法,但它以不同的方式返回时间,如下所示:

DateInterval {#1410 ▼
  interval: + 4d 10:42:00.0
  +"y": 0
  +"m": 0
  +"d": 4
  +"h": 10
  +"i": 42
  +"s": 0
  +"f": 0.0
  +"weekday": 0
  +"weekday_behavior": 0
  +"first_last_day_of": 0
  +"invert": 0
  +"days": 4
  +"special_type": 0
  +"special_amount": 0
  +"have_weekday_relative": 0
  +"have_special

所以我使用格式来获​​取时间,但我还需要一个格式来统一小时和秒,这是我的功能

public function compare(){

 return $diff = (date_diff(new DateTime('2020-12-24T00:00:00'),new DateTime('2020-12-28T10:42:00')));
 $diff = $interval->format('%h')+(($interval->format('%d')*24)+($interval->format('%m')*28*24)+($interval->format('%y')*365*28*24))*3600;
}

【问题讨论】:

  • 您在寻找更好的方法吗?
  • 函数中的第二行将永远不会被执行,因为控制权在第一行返回。
  • 如果有人回答您的问题,请点击复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己赢得了一些声誉。

标签: php


【解决方案1】:

使用strtotime(),将两个时间戳转换为 UNIX 格式,然后您可以使用秒轻松计算差异。

之后,使用a simple function将秒转换为HMS;

<?php


    $date_1 = strtotime('2020-12-24T00:00:00');
    $date_2 = strtotime('2020-12-28T10:42:00');
    
    // Get diff in seconds
    $diff = $date_2 - $date_1;
    
    // If $diff exeeds 72hours
    if ($diff > (72 * (60 * 60))) {
        echo "Exceed 72 hours" . PHP_EOL;
    }
    
    // Show diff + hms
    echo $diff . ' -- ' . toHMS($diff);
    
    
    function toHMS($seconds) {
      $t = round($seconds);
      return sprintf('%02d:%02d:%02d', ($t/3600),($t/60%60), $t%60);
    }

超过 72 小时

384120 -- 106:42:00

Try the above PHP code online!

【讨论】:

    【解决方案2】:

    你不需要使用date_diff DateTime 类本身有函数:

    
    $date1 = new DateTime('2006-04-12T12:30:00');
    $date2 = new DateTime('2006-04-14T11:30:00');
    
    $diff = $date2->diff($date1);
    
    $hours = $diff->h;
    
    
    

    【讨论】:

      【解决方案3】:

      我设法通过使用strtotime 找到了解决方案,如下所示

      $date_1 = strtotime('2020-12-28 00:00:00');
          $date_2 = strtotime('2020-12-31 00:00:01');
          $diff = $date_2 - $date_1;
          // 259200 = 72 hours in seconds
          if ($diff > 259200) {
            echo 'exceeds 72 hours';
         }else
         {
          echo 'ended on time';
         }
      

      通过减去日期,我只需要将结果与 259200 进行比较,即 72 小时的秒数,如果高于此值,则超出时间限制。

      【讨论】:

      • 这与我的回答有何不同?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多