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;
2
Answers
The dates you shown in the code are strings, they are not numerically "minorable". You need to convert them into a int of time first like this:
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 number1.1574074074074E-5
which then be rounded into 0.Your subtraction is using string values, not date values, so actually ends up as being 2022 – 2022, which equals zero…
(newer versions of PHP will complain "Notice: A non well formed numeric value encountered")
You could convert to instances of
DateTime
, and then determine the difference that way: