Sofia K.
Sofia K.

Reputation: 113

Date range between two dates with given time

I need to calculate the count of days between two given dates with time. For example the dates between '06/01/2019 09:00' and '06/02/2019 22:00' should count as 2 days for me. I tried the below code, but I don't get the result I need.

Any ideas on how to calculate the result?

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

Upvotes: 1

Views: 218

Answers (2)

Jikiwiki
Jikiwiki

Reputation: 115

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

There is one day difference, but I guess you also want to calculate the current day.

Upvotes: 0

u_mulder
u_mulder

Reputation: 54831

You can count total days as:

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);

Upvotes: 1

Related Questions