skip to Main Content

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


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

    Login or Signup to reply.
  2. 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;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search