Unforeseen results occur when calculating time difference in seconds in PHP by converting two dates to Unix timestamps.
P粉237029457
P粉237029457 2023-09-03 09:22:01
0
1
490
<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>
P粉237029457
P粉237029457

reply all(1)
P粉769413355

The problem is that you are using the date() function without parameters, try using this:

$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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!