我必须计算php中两个日期时间之间的小时数。这两个日期时间分别是分钟和秒,但是可以忽略。目标是获得小时数。这个和代表出现问题的差距。
您可以找到一些这段代码。我必须了解以下内容:
为了实现这一目标,我通过以下方式做到了这一点:
//delete minutes and seconds from datetime object
$datetime_start = date("Y-m-d h", strtotime($datetime_start));
$datetime_end = date("Y-m-d h", strtotime($datetime_end));
$datetime_start = $datetime_start.":00:00";
$datetime_end = $datetime_end.":00:00";
//create DateTime object
$datetime_start = new DateTime($datetime_start);
$datetime_end = new DateTime($datetime_end);
//get interval between two dates and fill array
$interval = $datetime_end->diff($datetime_start);
$details = array_intersect_key((array)$interval,array_flip(['y','m','d','h','i','s']));
$sum_of_hours = 0;
if(!empty($details["y"])){
$sum_of_hours = $sum_of_hours + $details["y"] * 365 * 24;
};
if(!empty($details["m"])){
$sum_of_hours = $sum_of_hours + $details["m"] * 30 * 24;
};
if(!empty($details["d"])){
$sum_of_hours = $sum_of_hours + $details["d"] * 24;
};
if(!empty($details["h"])){
$sum_of_hours = $sum_of_hours + $details["h"];
};
示例: 在这些日期“ 2018-06-30 02:00:05”和“ 2018-07-01 05:00:10”之间,我的间隔为1天3小时,导致27小时。 / p>
帮助的心意
答案 0 :(得分:0)
您可以将它们转换为unix时间戳,然后将它们彼此相减以获得秒差,然后除以60 * 60
得到小时:
floor(abs($datetime_end->getTimestamp() - $datetime_start->getTimestamp()) / (60 * 60))
这会为您的情况返回27
。
答案 1 :(得分:0)
<?php
$datetime1 = date_create('2018-06-30 02:00:05');
$datetime2 = date_create('2018-07-01 05:00:10');
$interval = date_diff($datetime1, $datetime2);
$hours = ($interval->days * 24) + $interval->h; // days to hour diff
echo $hours;
例如,输出27 ..