Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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:

$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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading