【问题标题】:How to get time difference in minutes in PHP如何在PHP中以分钟为单位获取时差
【发布时间】:2010-09-26 18:48:02
【问题描述】:

如何在 PHP 中计算两个日期时间之间的分钟差?

【问题讨论】:

    标签: php date time minute


    【解决方案1】:

    以上答案适用于旧版本的 PHP。由于 PHP 5.3 已成为标准,请使用 DateTime 类进行任何日期计算。 例如。

    $start_date = new DateTime('2007-09-01 04:10:58');
    $since_start = $start_date->diff(new DateTime('2012-09-11 10:25:00'));
    echo $since_start->days.' days total<br>';
    echo $since_start->y.' years<br>';
    echo $since_start->m.' months<br>';
    echo $since_start->d.' days<br>';
    echo $since_start->h.' hours<br>';
    echo $since_start->i.' minutes<br>';
    echo $since_start->s.' seconds<br>';
    

    $since_start 是一个DateInterval 对象。请注意,days 属性是可用的(因为我们使用了 DateTime 类的 diff 方法来生成 DateInterval 对象)。

    上面的代码会输出:

    总共 1837 天
    5 年
    0 个月
    10 天
    6 小时
    14 分钟
    2 秒

    获取总分钟数:

    $minutes = $since_start->days * 24 * 60;
    $minutes += $since_start->h * 60;
    $minutes += $since_start->i;
    echo $minutes.' minutes';
    

    这将输出:

    2645654 分钟

    这两个日期之间的实际分钟数。 DateTime 类将考虑夏令时(取决于时区),而“旧方式”则不会。阅读有关日期和时间的手册http://www.php.net/manual/en/book.datetime.php

    【讨论】:

    • Pitty DateInterval 没有 inSeconds() 之类的方法或类似的方法,现在我需要计算以秒为单位的差异的所有地方都是代码重复。
    • @barius 或者您可以编写一个包装重复代码的函数,甚至扩展 DateTime 而不重复您的代码。
    • +1 是撰写此评论时唯一正确的答案。
    • 使用新的 DateTime 类很好,但为什么要生成一个 DateInterval ,然后必须如此笨拙地解码呢? $dateFrom = new DateTime('2007-09-01 04:10:58'); $dateTo = new DateTime('2012-09-11 10:25:00'); echo ($dateTo-&gt;getTimestamp()-$dateFrom-&gt;getTimestamp())/60 ;
    • 有人可以向我解释为什么这比上面的strtotime 答案更好吗?当 Procedural 至少是有效(并且更简洁)的解决方案时,这似乎是 OOP 的一个案例。
    【解决方案2】:

    答案如下:

    $to_time = strtotime("2008-12-13 10:42:00");
    $from_time = strtotime("2008-12-13 10:21:00");
    echo round(abs($to_time - $from_time) / 60,2). " minute";
    

    【讨论】:

    • abs() 函数如果有人想检查负时间也不需要!
    • 对于那些想知道的人,/ 60,2 的意思是:除以 60,四舍五入到小数点后两位。
    • strtotime 不可靠,避免。仅适用于特定日期格式,主要与美国相关。
    • strtotime 可能已经过时,但如果使用得当,它并非不可靠。理所当然地,您需要使用一致的日期格式才能正确读取(或解析)日期。请参阅ISO 8601,不要责怪工具:=)
    【解决方案3】:

    从未来的最大一中减去过去的最大一并除以60。

    时间以 Unix 格式完成,所以它们只是一个大数字,显示从 January 1, 1970, 00:00:00 GMT 开始的秒数

    【讨论】:

    • @Jerald 这个解决方案如何为您工作?你介意至少简要介绍一下吗?谢谢。
    • @WafieAli $nInterval = strtotime($sDate2) - strtotime($sDate1);这将以秒为单位返回时差,然后您可以像这样除以 60。 $nInterval = $nInterval/60;
    • +1 用于解释需要做什么,而不是使用没有方法的无用 DateInterval 类:返回差异以分钟为单位。跨度>
    【解决方案4】:
    <?php
    $date1 = time();
    sleep(2000);
    $date2 = time();
    $mins = ($date2 - $date1) / 60;
    echo $mins;
    ?>
    

    【讨论】:

    • 您能解释一下为什么需要一些sleep 来计算日期差吗?
    • 有什么比快速睡眠更好的方式来利用你的时间,同时等待另一个时间来比较。虽然理论上这应该给你一个 2 的答案,这可以帮助人们试图理解这个公式,确认它是正确的。
    【解决方案5】:
    <?php
    $start = strtotime('12:01:00');
    $end = strtotime('13:16:00');
    $mins = ($end - $start) / 60;
    echo $mins;
    ?>
    

    输出:

    75
    

    【讨论】:

      【解决方案6】:

      它适用于我的程序,我正在使用date_diff,你可以查看date_diffhere 上的手册。

      $start = date_create('2015-01-26 12:01:00');
      $end = date_create('2015-01-26 13:15:00');
      $diff=date_diff($end,$start);
      print_r($diff);
      

      你得到你想要的结果。

      【讨论】:

      • 奇怪,对我来说,执行该代码并没有提供以分钟为单位的时差
      • 这只有在你想输出“1hr 14mins”时才有用。例如,如果您只想要几分钟),则必须进行数学运算: ($diff->h * 60) + $diff->i)
      【解决方案7】:

      时区的另一种方式。

      $start_date = new DateTime("2013-12-24 06:00:00",new DateTimeZone('Pacific/Nauru'));
      $end_date = new DateTime("2013-12-24 06:45:00", new DateTimeZone('Pacific/Nauru'));
      $interval = $start_date->diff($end_date);
      $hours   = $interval->format('%h'); 
      $minutes = $interval->format('%i');
      echo  'Diff. in minutes is: '.($hours * 60 + $minutes);
      

      【讨论】:

      • 如果你也想要几天,那么你添加 $days = $interval-&gt;format('%d'); 并且差异是 ($days * 1440 + $hours * 60 + $minutes) 。几个月,几年=>相同的逻辑
      【解决方案8】:

      我为我的一个博客站点编写了这个函数(过去日期和服务器日期之间的差异)。它会给你这样的输出

      “49 秒前”、“20 分钟前”、“21 小时前”等

      我使用了一个函数,可以让我知道过去日期和服务器日期之间的差异。

      <?php
      
      //Code written by purpledesign.in Jan 2014
      function dateDiff($date)
      {
          $mydate= date("Y-m-d H:i:s");
          $theDiff="";
          //echo $mydate;//2014-06-06 21:35:55
          $datetime1 = date_create($date);
          $datetime2 = date_create($mydate);
          $interval = date_diff($datetime1, $datetime2);
          //echo $interval->format('%s Seconds %i Minutes %h Hours %d days %m Months %y Year    Ago')."<br>";
          $min=$interval->format('%i');
          $sec=$interval->format('%s');
          $hour=$interval->format('%h');
          $mon=$interval->format('%m');
          $day=$interval->format('%d');
          $year=$interval->format('%y');
          if($interval->format('%i%h%d%m%y')=="00000") {
              //echo $interval->format('%i%h%d%m%y')."<br>";
              return $sec." Seconds";
          } else if($interval->format('%h%d%m%y')=="0000"){
              return $min." Minutes";
          } else if($interval->format('%d%m%y')=="000"){
              return $hour." Hours";
          } else if($interval->format('%m%y')=="00"){
              return $day." Days";
          } else if($interval->format('%y')=="0"){
              return $mon." Months";
          } else{
              return $year." Years";
          }    
      }
      ?>
      

      将其保存为文件,假设为“date.php”。像这样从另一个页面调用函数

      <?php
       require('date.php');
       $mydate='2014-11-14 21:35:55';
       echo "The Difference between the server's date and $mydate is:<br> ";
       echo dateDiff($mydate);
      ?>
      

      当然你可以修改函数来传递两个值。

      【讨论】:

        【解决方案9】:

        我想这会对你有所帮助

        function calculate_time_span($date){
            $seconds  = strtotime(date('Y-m-d H:i:s')) - strtotime($date);
        
                $months = floor($seconds / (3600*24*30));
                $day = floor($seconds / (3600*24));
                $hours = floor($seconds / 3600);
                $mins = floor(($seconds - ($hours*3600)) / 60);
                $secs = floor($seconds % 60);
        
                if($seconds < 60)
                    $time = $secs." seconds ago";
                else if($seconds < 60*60 )
                    $time = $mins." min ago";
                else if($seconds < 24*60*60)
                    $time = $hours." hours ago";
                else if($seconds < 24*60*60)
                    $time = $day." day ago";
                else
                    $time = $months." month ago";
        
                return $time;
        }
        

        【讨论】:

        • 请在您的代码中添加一些解释,以便 OP 可以从中学习
        • 几分钟$minutes = floor(($seconds/60)%60);
        【解决方案10】:

        这就是我在 php > 5.2 中显示“xx 次前”的方式 .. 这里有更多关于 DateTime 对象的信息

        //Usage:
        $pubDate = $row['rssfeed']['pubDates']; // e.g. this could be like 'Sun, 10 Nov 2013 14:26:00 GMT'
        $diff = ago($pubDate);    // output: 23 hrs ago
        
        // Return the value of time different in "xx times ago" format
        function ago($timestamp)
        {
        
            $today = new DateTime(date('y-m-d h:i:s')); // [2]
            //$thatDay = new DateTime('Sun, 10 Nov 2013 14:26:00 GMT');
            $thatDay = new DateTime($timestamp);
            $dt = $today->diff($thatDay);
        
            if ($dt->y > 0){
                $number = $dt->y;
                $unit = "year";
            } else if ($dt->m > 0) {
                $number = $dt->m;
                $unit = "month";
            } else if ($dt->d > 0) {
                $number = $dt->d;
                $unit = "day";
            } else if ($dt->h > 0) {
                $number = $dt->h;
                $unit = "hour";
            } else if ($dt->i > 0) {
                $number = $dt->i;
                $unit = "minute";
            } else if ($dt->s > 0) {
                $number = $dt->s;
                $unit = "second";
            }
            
            $unit .= $number  > 1 ? "s" : "";
         
            $ret = $number." ".$unit." "."ago";
            return $ret;
        }
        

        【讨论】:

          【解决方案11】:
          function date_getFullTimeDifference( $start, $end )
          {
          $uts['start']      =    strtotime( $start );
                  $uts['end']        =    strtotime( $end );
                  if( $uts['start']!==-1 && $uts['end']!==-1 )
                  {
                      if( $uts['end'] >= $uts['start'] )
                      {
                          $diff    =    $uts['end'] - $uts['start'];
                          if( $years=intval((floor($diff/31104000))) )
                              $diff = $diff % 31104000;
                          if( $months=intval((floor($diff/2592000))) )
                              $diff = $diff % 2592000;
                          if( $days=intval((floor($diff/86400))) )
                              $diff = $diff % 86400;
                          if( $hours=intval((floor($diff/3600))) )
                              $diff = $diff % 3600;
                          if( $minutes=intval((floor($diff/60))) )
                              $diff = $diff % 60;
                          $diff    =    intval( $diff );
                          return( array('years'=>$years,'months'=>$months,'days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
                      }
                      else
                      {
                          echo "Ending date/time is earlier than the start date/time";
                      }
                  }
                  else
                  {
                      echo "Invalid date/time data detected";
                  }
          }
          

          【讨论】:

            【解决方案12】:

            一个更通用的版本,以天、小时、分钟或秒返回结果,包括分数/小数:

            function DateDiffInterval($sDate1, $sDate2, $sUnit='H') {
            //subtract $sDate2-$sDate1 and return the difference in $sUnit (Days,Hours,Minutes,Seconds)
                $nInterval = strtotime($sDate2) - strtotime($sDate1);
                if ($sUnit=='D') { // days
                    $nInterval = $nInterval/60/60/24;
                } else if ($sUnit=='H') { // hours
                    $nInterval = $nInterval/60/60;
                } else if ($sUnit=='M') { // minutes
                    $nInterval = $nInterval/60;
                } else if ($sUnit=='S') { // seconds
                }
                return $nInterval;
            } //DateDiffInterval
            

            【讨论】:

            • 请在您的代码中添加一些解释,以便 OP 可以从中学习
            【解决方案13】:

            减去时间再除以60。

            这是一个以分钟为单位计算从2019/02/01 10:23:45 开始的经过时间的示例:

            $diff_time=(strtotime(date("Y/m/d H:i:s"))-strtotime("2019/02/01 10:23:45"))/60;
            

            【讨论】:

              【解决方案14】:

              DateTime::diff 很酷,但是对于这种需要单个单位结果的计算来说很尴尬。手动减去时间戳效果更好:

              $date1 = new DateTime('2020-09-01 01:00:00');
              $date2 = new DateTime('2021-09-01 14:00:00');
              $diff_mins = abs($date1->getTimestamp() - $date2->getTimestamp()) / 60;
              

              【讨论】:

                【解决方案15】:

                我找到两个日期之间差异的解决方案在这里。使用此功能,您可以找到秒、分钟、小时、天、年和月等差异。

                function alihan_diff_dates($date = null, $diff = "minutes") {
                 $start_date = new DateTime($date);
                 $since_start = $start_date->diff(new DateTime( date('Y-m-d H:i:s') )); // date now
                 print_r($since_start);
                 switch ($diff) {
                    case 'seconds':
                        return $since_start->s;
                        break;
                    case 'minutes':
                        return $since_start->i;
                        break;
                    case 'hours':
                        return $since_start->h;
                        break;
                    case 'days':
                        return $since_start->d;
                        break;      
                    default:
                        # code...
                        break;
                 }
                }
                

                您可以开发此功能。我测试并为我工作。 DateInterval 对象输出在这里:

                /*
                DateInterval Object ( [y] => 0 [m] => 0 [d] => 0 [h] => 0 [i] => 5 [s] => 13 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 0 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 ) 
                */
                

                函数用法:

                $date = 过去的日期, $diff = 类型 例如:“分钟”、“天”、“秒”

                $diff_mins = alihan_diff_dates("2019-03-24 13:24:19", "minutes");
                

                祝你好运。

                【讨论】:

                  【解决方案16】:
                  $date1=date_create("2020-03-15");
                  $date2=date_create("2020-12-12");
                  $diff=date_diff($date1,$date2);
                  echo $diff->format("%R%a days");
                  

                  有关详细的格式说明符,请访问link

                  【讨论】:

                    【解决方案17】:

                    另一种以分钟为单位计算差异的简单方法。请注意,这是一个在 1 年范围内计算的样本。更多详情请点击here

                    $origin = new DateTime('2021-02-10 09:46:32');
                    $target = new DateTime('2021-02-11 09:46:32');
                    $interval = $origin->diff($target);
                    echo (($interval->format('%d')*24) + $interval->format('%h'))*60; //1440 (difference in minutes)
                    

                    【讨论】:

                      【解决方案18】:

                      这会有所帮助....

                      function get_time($date,$nosuffix=''){
                          $datetime = new DateTime($date);
                          $interval = date_create('now')->diff( $datetime );
                          if(empty($nosuffix))$suffix = ( $interval->invert ? ' ago' : '' );
                          else $suffix='';
                          //return $interval->y;
                          if($interval->y >=1)        {$count = date(VDATE, strtotime($date)); $text = '';}
                          elseif($interval->m >=1)    {$count = date('M d', strtotime($date)); $text = '';}
                          elseif($interval->d >=1)    {$count = $interval->d; $text = 'day';} 
                          elseif($interval->h >=1)    {$count = $interval->h; $text = 'hour';}
                          elseif($interval->i >=1)    {$count = $interval->i; $text = 'minute';}
                          elseif($interval->s ==0)    {$count = 'Just Now'; $text = '';}
                          else                        {$count = $interval->s; $text = 'second';}
                          if(empty($text)) return '<i class="fa fa-clock-o"></i> '.$count;
                          return '<i class="fa fa-clock-o"></i> '.$count.(($count ==1)?(" $text"):(" ${text}s")).' '.$suffix;     
                      }
                      

                      【讨论】:

                      • 请在您的代码中添加一些解释,以便 OP 可以从中学习
                      【解决方案19】:

                      我找到了很多解决方案,但我从来没有得到正确的解决方案。但是我创建了一些代码来查找分钟,请检查它。

                      <?php
                      
                        $time1 = "23:58";
                        $time2 = "01:00";
                        $time1 = explode(':',$time1);
                        $time2 = explode(':',$time2);
                        $hours1 = $time1[0];
                        $hours2 = $time2[0];
                        $mins1 = $time1[1];
                        $mins2 = $time2[1];
                        $hours = $hours2 - $hours1;
                        $mins = 0;
                        if($hours < 0)
                        {
                          $hours = 24 + $hours;
                        }
                        if($mins2 >= $mins1) {
                              $mins = $mins2 - $mins1;
                          }
                          else {
                            $mins = ($mins2 + 60) - $mins1;
                            $hours--;
                          }
                          if($mins < 9)
                          {
                            $mins = str_pad($mins, 2, '0', STR_PAD_LEFT);
                          }
                          if($hours < 9)
                          {
                            $hours =str_pad($hours, 2, '0', STR_PAD_LEFT);
                          }
                      echo $hours.':'.$mins;
                      ?>
                      

                      它以小时和分钟为单位给出输出,例如 01 小时 02 分钟,如 01:02

                      【讨论】:

                        【解决方案20】:

                        这是一个简单的单行:

                        $start = new DateTime('yesterday');
                        $end = new DateTime('now');
                        $diffInMinutes = iterator_count(new \DatePeriod($start, new \DateInterval('PT1M'), $end));
                        

                        【讨论】:

                          【解决方案21】:

                          试试这个

                          $now = \Carbon\Carbon::now()->toDateString(); // get current time 
                                       $a = strtotime("2012-09-21 12:12:22"); 
                                       $b = strtotime($now);
                                       $minutes = ceil(($a - $b) / 3600); it will get ceiling value 
                          

                          【讨论】:

                            猜你喜欢
                            • 2021-12-01
                            • 1970-01-01
                            • 2016-10-23
                            • 1970-01-01
                            • 1970-01-01
                            • 2013-11-04
                            • 2019-03-06
                            • 1970-01-01
                            相关资源
                            最近更新 更多