0

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;
michaelmcgurk
  • 6,367
  • 23
  • 94
  • 190

2 Answers2

3

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.

Henryc17
  • 851
  • 4
  • 16
  • Amazing. I've just replace $datediff with $number_of_days to resolve it. Thank you so much. – michaelmcgurk Nov 11 '22 at 11:36
  • note: if you use this method and division, and cross a daylight saving time change, then you'll end up with a fractional part, and possibly the wrong number of integer days, so bear that in mind. – Paul Crozer Nov 11 '22 at 11:49
1

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:

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

// convert to DateTime
$dtEnd = DateTime::createFromFormat('!Y-m-d', $end);
$dtStart = DateTime::createFromFormat('!Y-m-d', $start);

// get the difference in days
$days = $dtEnd->diff($dtStart)->format('%a') + 1;
Paul Crozer
  • 68
  • 1
  • 10