Unforeseen results occur when calculating time difference in seconds in PHP by converting two dates to Unix timestamps.
<p>As per the title, I am trying to find the difference in seconds and then convert those seconds to days and hours. </p>
<p>After reading and following similar questions, I built a function that adds the hour, day, week, month, or year I want to today's datetime, and I get the correct results from this part. </p>
<p> However, I then tried converting the two dates (start date and move date) to unix timestamps, subtracting both timestamps to find the difference between the two dates in seconds, and then converting I don't get the results I expected for days or minutes (/86400 and /3600). </p>
<p>This is the code..</p>
<pre class="brush:php;toolbar:false;"><?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");
?></pre>
<p>The current result is..</p>
<blockquote>
<p>2023-01-04 09:37:51 > 19361 days or 464673 hours</p>
</blockquote>
<p>I expected it to be like this</p>
<blockquote>
<p>2023-01-04 09:37:51 > 1 day or 24 hours</p>
</blockquote></p>