Webgen Webgen - 2 months ago 7
PHP Question

Calculation of no of hours & more on using date Y-m-d H:i:s

I have below 2 dates with hours & time.
Format: Y-m-d H:i:s

$day1 = 2016-10-01 02:00:00
$day2 = 2016-10-02 03:00:00


calculating no of days using

$interval = $day1->diff($day2);
echo $interval->format('%a');


this gives me 1 day but actually it must be 2 days cause it more than 25hours.

So on the basis of hours how can we get no of days?

Answer

From what you mentioned, we are supposed to round it to the next day value if it exceeds 24 hrs.

The logic is pretty simple.

  1. Store the hour difference between two dates in $hoursDiff.
  2. Calculate the no. of days i.e the floor value $days.
  3. Check if there's any additional difference e.g 1 day + remaining 1 hour $remaining
  4. If remaining value exists then add 1 day to $day. Otherwise keep it as it is.

    $day1 = '2016-10-01 02:00:00'; // Declare as string
    $day2 = '2016-10-02 03:00:00'; // Declare as string
    $hoursDiff = round((strtotime($day2) - strtotime($day1))/3600, 1); 
    $days = floor($hoursDiff / 24); 
    $remaining = ($hoursDiff % 24);
    $dayDiff = $remaining ? ($days + 1) : $days;
    
Comments