php中两个日期时间之间的差异

时间:2014-03-26 13:52:26

标签: php

我想在HOURS中计算startdatetime和enddatetime之间的小时差异。

日期格式为MM / DD / YYYY,时间格式为HH:MM:SS格式

以下是代码:

$strt_date  = "03/24/2014";
$start_time = "23:14:57";
$end_date = "03/25/2014";
$end_time = "07:34:55";

$datetime1 = new DateTime($strt_date $start_time);
$datetime2 = new DateTime($end_date $end_time);
$diff = $datetime1->diff($datetime2);   
$diff1 =  $diff->format('%h');

2 个答案:

答案 0 :(得分:1)

您的DateTime构造函数的参数不正确。如果您需要在日期和时间之间留出空格,则需要明确添加它们。

$datetime1 = new DateTime("$strt_date $start_time");
$datetime2 = new DateTime("$end_date $end_time");

$datetime1 = new DateTime($strt_date . ' ' . $start_time);
$datetime2 = new DateTime($end_date . ' ' . $end_time);

答案 1 :(得分:0)

$date1 = new DateTime($row['start']);
$date2 = new DateTime($row['end']);

$duration = $date2->diff($date1);

$hours = $duration->d*24 + $duration->h + $duration->i/60;
echo  $hours.'<br> ';