如何在PHP中获得几分钟的时差

Tom*_*ski 252 php time date minute

如何计算PHP中两个日期时间之间的微小差异?

小智 370

以上答案适用于旧版本的PHP.现在使用DateTime类进行任何日期计算,因为PHP 5.3是常态.例如.

$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>';
Run Code Online (Sandbox Code Playgroud)

$ 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';
Run Code Online (Sandbox Code Playgroud)

这将输出:

2645654分钟

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

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

小智 328

这是答案:

$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";
Run Code Online (Sandbox Code Playgroud)

  • 对于那些想知道的人,`/ 60,2`意味着:除以60,舍入到最接近的两位小数. (33认同)
  • `strtotime`可能已经过时但如果你正确使用它并不是不可靠的.按理说,您需要使用一致的日期格式才能正确读取(或解析)日期.参见`ISO 8601`并且不要责怪工具:=) (13认同)
  • 如果有人希望检查负片时间,则不需要abs()函数! (4认同)
  • strtotime不可靠,避免.仅适用于特定日期格式,主要与美国相关. (3认同)

Oli*_*Oli 85

从过去最多的一个减去过去最多的一个并除以60.

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

  • @WafieAli $ nInterval = strtotime($ sDate2) - strtotime($ sDate1); 这将以秒为单位返回时间差,然后你可以像这样除以60.$ nInterval = $ nInterval/60; (5认同)
  • @Jerald 这个解决方案如何为你工作?你介意至少简要介绍一下吗?谢谢。 (2认同)

Tom*_*Tom 32

<?php
$date1 = time();
sleep(2000);
$date2 = time();
$mins = ($date2 - $date1) / 60;
echo $mins;
?>
Run Code Online (Sandbox Code Playgroud)

  • 与快速入睡相比,还有一种更好的方式来利用您的时间等待另一个时间进行比较。尽管从理论上讲应该给您2的答案,这可以帮助尝试理解该公式的人,确认它是正确的。 (2认同)

小智 21

<?php
$start = strtotime('12:01:00');
$end = strtotime('13:16:00');
$mins = ($end - $start) / 60;
echo $mins;
?>
Run Code Online (Sandbox Code Playgroud)

输出:

75
Run Code Online (Sandbox Code Playgroud)


Şaf*_*zer 21

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;
Run Code Online (Sandbox Code Playgroud)


yus*_*san 15

它适用于我的程序,我使用date_diff,你可以date_diff这里检查手册.

$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);
Run Code Online (Sandbox Code Playgroud)

你得到你想要的结果.

  • 仅当您想输出“1hr 14mins”时这才有用。例如,如果您只想要几分钟),则必须进行数学计算: ($diff-&gt;h * 60) + $diff-&gt;i) (2认同)

Muh*_*mad 12

时区的另一种方式.

$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);
Run Code Online (Sandbox Code Playgroud)

  • 怎么会有天差?不行! (4认同)
  • 如果你想要几天,也可以添加`$ days = $ interval-> format('%d');`和差异是`($ days*1440 + $ hours*60 + $ minutes)`.几个月,几年=>相同的逻辑 (4认同)

Raj*_*rma 11

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

"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";
   }

}
?>
Run Code Online (Sandbox Code Playgroud)

将其保存为文件,假设为"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);
?>
Run Code Online (Sandbox Code Playgroud)

当然,您可以修改函数以传递两个值.


Yub*_*rel 10

我想这会对你有所帮助

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;
}
Run Code Online (Sandbox Code Playgroud)


Vee*_*dra 9

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";
        }
}
Run Code Online (Sandbox Code Playgroud)


hri*_*iya 7

这就是我在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;
}
Run Code Online (Sandbox Code Playgroud)


bes*_*ple 7

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

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
Run Code Online (Sandbox Code Playgroud)


Mus*_*afa 7

减去时间并除以 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;
Run Code Online (Sandbox Code Playgroud)