php时间戳之间的时间差(以小时为单位)


Time difference between php timestamps in hours

我有一个使用php time()函数生成的php时间戳1331875634

我有使用相同函数生成的当前时间戳。

<?php
$time1 = "1331875634";
$time2 = time();
echo $differencem; //time difference in minutes
echo $differenceh; //time difference in hours
?>

我想在几分钟内知道这两者之间的区别。分钟可以除以60,以小时为单位。

如果你减去它们,你会得到以秒为单位的差异,所以除以60得到分钟,再除以60得到小时。

我创建此代码是为了采用标准的PHP UNIX TIMESTAMP,计算时间差并返回标准时间或专用时间格式。这对于确定项目的时间和计算获得结果所需的时间非常有用。

function timerFormat($start_time, $end_time, $std_format = false)
{       
$total_time = $end_time - $start_time;
$days       = floor($total_time /86400);        
$hours      = floor($total_time /3600);     
$minutes    = intval(($total_time/60) % 60);        
$seconds    = intval($total_time % 60);     
$results = "";
if($std_format == false)
{
  if($days > 0) $results .= $days . (($days > 1)?" days ":" day ");     
  if($hours > 0) $results .= $hours . (($hours > 1)?" hours ":" hour ");        
  if($minutes > 0) $results .= $minutes . (($minutes > 1)?" minutes ":" minute ");
  if($seconds > 0) $results .= $seconds . (($seconds > 1)?" seconds ":" second ");
}
else
{
  if($days > 0) $results = $days . (($days > 1)?" days ":" day ");
  $results = sprintf("%s%02d:%02d:%02d",$results,$hours,$minutes,$seconds);
}
return $results;
}
Example:
$begin_routine_time = time();
echo(timerFormat($begin_routine_time, $time()));
$datetime1 = new DateTime(date('Y-m-d H:i:s', 1331875634));
$datetime2 = new DateTime(date('Y-m-d H:i:s'));
$oDiff = $datetime1->diff($datetime2);
echo $oDiff->y.' Years <br/>';
echo $oDiff->m.' Months <br/>';
echo $oDiff->d.' Days <br/>';
echo $oDiff->h.' Hours <br/>';
echo $oDiff->i.' Minutes <br/>';
echo $oDiff->s.' Seconds <br/>';

有一次我需要将秒转换为时间,比如1天03:34:13天小时:分钟:秒

我写了这个函数

function sECONDS_TO_HMS($seconds)
  {
     $days = floor($seconds/86400);
     $hrs = floor($seconds/3600);
     $mins = intval(($seconds / 60) % 60); 
     $sec = intval($seconds % 60);
        if($days>0){
          //echo $days;exit;
          $hrs = str_pad($hrs,2,'0',STR_PAD_LEFT);
          $hours=$hrs-($days*24);
          $return_days = $days." Days ";
          $hrs = str_pad($hours,2,'0',STR_PAD_LEFT);
     }else{
      $return_days="";
      $hrs = str_pad($hrs,2,'0',STR_PAD_LEFT);
     }
     $mins = str_pad($mins,2,'0',STR_PAD_LEFT);
     $sec = str_pad($sec,2,'0',STR_PAD_LEFT);
     return $return_days.$hrs.":".$mins.":".$sec;
  }
echo sECONDS_TO_HMS(65); // 00:01:05
echo sECONDS_TO_HMS(76325); //21:12:05
echo sECONDS_TO_HMS(345872); // 4 Days 00:04:32 

我认为这对你有帮助。