时间为am和pm的两个时间之间的时差

时间:2019-02-12 10:48:01

标签: php datetime

我有两次,就像这样:

$date1 = strtotime("02/12/2019 10:10:54 am");  
     $date2 = strtotime("02/12/2019 10:11:07 pm");
     $diff = abs($date2 - $date1); 
     $years = floor($diff / (365*60*60*24)); 
     $months = floor(($diff - $years * 365*60*60*24) 
                           / (30*60*60*24));
     $days = floor(($diff - $years * 365*60*60*24 -  
        $months*30*60*60*24)/ (60*60*24)); 
    $hours = floor(($diff - $years * 365*60*60*24  
   - $months*30*60*60*24 - $days*60*60*24) 
                               / (60*60));
    $minutes = floor(($diff - $years * 365*60*60*24  
     - $months*30*60*60*24 - $days*60*60*24  
                  - $hours*60*60)/ 60);
  $seconds = floor(($diff - $years * 365*60*60*24  
 - $months*30*60*60*24 - $days*60*60*24 
        - $hours*60*60 - $minutes*60));
  printf(" %d days, %d hours, "
 . "%d minutes, %d seconds", 
         $days, $hours, $minutes, $seconds); 

我想计算它们之间的差异,但这不起作用。

1 个答案:

答案 0 :(得分:2)

使用DateTime类要容易得多,该类具有一个diff方法,该方法可以产生一个DateInterval对象,该对象可以以您喜欢的任何格式输出差异:

$date1 = new DateTime("02/12/2019 10:10:54 am"); 
$date2 = new DateTime("02/12/2019 10:11:07 pm");
$diff = $date1->diff($date2);
echo $diff->format('%y years, %m months, %d days, %h hours, %i minutes and %s seconds');

输出:

0 years, 0 months, 0 days, 12 hours, 0 minutes and 13 seconds

Demo on 3v4l.org