search

Home  >  Q&A  >  body text

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>
P粉237029457P粉237029457458 days ago614

reply all(1)I'll reply

  • P粉769413355

    P粉7694133552023-09-04 00:23:10

    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

    reply
    0
  • Cancelreply