给定时间的两个日期之间的日期范围

时间:2019-06-01 10:31:24

标签: php date-range

我需要计算两个给定日期之间随时间的天数。例如,对于我来说,“ 06/01/2019 09:00”和“ 06/02/2019 22:00”之间的日期应算作2天。我尝试了以下代码,但没有得到所需的结果。

关于如何计算结果的任何想法?

$to = $_GET['end_date'];
$dteStart = new DateTime($from); 
$dteEnd   = new DateTime($to); 
$diff  = $dteStart->diff($dteEnd); 
print $diff->format("%H:%I");

2 个答案:

答案 0 :(得分:0)

您可以将总天数计算为:

print $diff->format('%D') + (0 < $diff->format('%H') ? 1 : 0);
// %D - gives you number of days between dates
// and if there're more hours between dates - add one day 

// probably you also want to consider minutes, 
// so as "1 day 10 minutes" diff should also be 
// considered as 2 days, then:
print $diff->format('%D') + ((0 < $diff->format('%H') || 0 < $diff->format('%I')) ? 1 : 0);

答案 1 :(得分:0)

$diff  = $dteStart->diff($dteEnd)->days + 1;
echo $diff;

有一天的差异,但是我想您也想计算当天的数据。