1

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");
Sofia K.
  • 113
  • 7
  • 1
    Possible duplicate of [How to count days between two dates in PHP?](https://stackoverflow.com/questions/3653882/how-to-count-days-between-two-dates-in-php) – user2653663 Jun 01 '19 at 13:41
  • Yes it works, but without having set timerange. What I need is to count days between two days based on given time. For example 06/02/2019 09:00 and 06/03/2019 09:00, should count as 1 day and 06/01/2019 09:00' and '06/02/2019 22:00' should count as 2 days. – Sofia K. Jun 01 '19 at 18:47

2 Answers2

1

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);
u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • Thanks so much for your response. I tried your code and it seems to work for the dates I gave above. But when I have 06/02/2019 09:00 06/03/2019 09:00, this should count as 1 day, and the result I get is 2 days. So what I need is, to count +1 day when 24 hours have passed. – Sofia K. Jun 01 '19 at 18:35
  • I guess something went wrong with the cache of my site and it counted 2 days. I tried again with your code and it works perfect! Thank you sooooo much for your help!!! – Sofia K. Jun 03 '19 at 09:01
  • One last question. Is it also possible to count 06/02/2019 22:00 and 06/03/2019 22:30 as 2 days? I seems that it counts as 2 days when an hour after the 24hours have passed. – Sofia K. Jun 03 '19 at 14:29
  • Did you __notice__ second block of code in my answer? – u_mulder Jun 03 '19 at 14:44
  • Yeah I missed that after you posted the link to the editor.. Thanks again!! – Sofia K. Jun 03 '19 at 14:55
0
$diff  = $dteStart->diff($dteEnd)->days + 1;
echo $diff;

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

Jikiwiki
  • 115
  • 1
  • 8