php

Datediff round returns zero


I'm trying to run a datediff. I essentially want to say the number of days between 1st November 2022 and 1st November 2022 is ONE day.

When I attempt this, $number_of_days returned is 0. Can someone explain why this is and how to resolve?

$end = "2022-11-01";
$start = "2022-11-01";

$datediff = ($end - $start) + 1; // tried to fix

echo $datediff;

echo '<hr>';

echo ($datediff / (60 * 60 * 24));

$number_of_days = round($datediff / (60 * 60 * 24));

echo '<hr>';

echo $number_of_days;

Solution

  • The dates you shown in the code are strings, they are not numerically "minusable". You need to convert them into an int of time first like this:

    $end = strtotime("2022-11-01");
    $start = strtotime("2022-11-01");
    
    $datediff = (($end - $start)/60/60/24) + 1;
    

    Why doesn't it work: If you try to subtract strings like this, PHP will auto-convert the strings into the boolean value true and then convert them into the integer 1. You divided it by (60 * 60 * 24) which results in a very small number 1.1574074074074E-5 which then be rounded into 0.