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
440

As per the title, I am trying to find the difference in seconds and then convert those seconds to days and hours.

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.

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

This is the code..

 " . floor($difference/86400) . " days or " . floor($difference/3600) . " hours"; } echo dateTimeShift($dateTimeNow, "1", "day"); ?>

The current result is..

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

I expected it to be like this

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

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 . " 
" . floor($difference/86400) . " days or " . floor($difference/3600) . " hours"; } echo dateTimeShift($dateTimeNow, "1", "day");

Output:

2023-01-04 09:57:31 
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!