Search code examples
phpdatetimedate-conversiondate-difference

PHP convert two dates to unix timestamps, subtract the two timestamps to find the difference between the two dates in seconds. unxepected results?


As per title, I'm trying to find the differance in seconds then covert these seconds to days and hours.

Having read and followed similar questions I have built a function that adds my desired hours, days, weeks, months or years to todays datetime and I am getting the correct result from that part of it.

However I then try and convert the two dates (start date and shifted date) to unix timestamps, subtract the two timestamps to find the difference between the two dates in seconds then convert to days or mins (/86400 and /3600) I am not getting the result I expected.

Here is the code..

<?php
$dateTimeNow = date();

function dateTimeShift($dateTimeIn, $lengthNum, $lengthWord) {
$shifted = date("Y-m-d H:i:s", strtotime($dateTimeIn." + $lengthNum $lengthWord"));
$difference = strtotime($shifted)-strtotime($dateTimeIn);
return $shifted . " <br> " . floor($difference/86400) . " days or " . floor($difference/3600) . " hours";
}

echo dateTimeShift($dateTimeNow, "1", "day");
?>

The result from this is currently..

2023-01-04 09:37:51 > 19361 days or 464673 hours

I expected it to be

2023-01-04 09:37:51 > 1 day or 24 hours


Solution

  • The problem is that you are using date() function without arguments, try with this one:

    $dateTimeNow = date("Y-m-d H:i:s");
    
    function dateTimeShift($dateTimeIn, $lengthNum, $lengthWord) {
        $shifted = date("Y-m-d H:i:s", strtotime($dateTimeIn." + $lengthNum $lengthWord"));
        $difference = strtotime($shifted)-strtotime($dateTimeIn);
        return $shifted . " <br> " . floor($difference/86400) . " days or " . floor($difference/3600) . " hours";
    }
    
    echo dateTimeShift($dateTimeNow, "1", "day");
    

    Output:

    2023-01-04 09:57:31 <br> 1 days or 24 hours