The Difference Between Time Stamps in PHP

104 22

    Structure

    • PHP time stamps have an integer value that represent how many seconds have passed between the Unix Epoch (January 1 1970, 00:00:00 GMT) and the current time. The "time()" function returns the current Unix time stamp. A typical PHP time stamp will appear as "1307826891."

    Converting Time Stamps into DateTime

    • Converting PHP time stamps into DateTime objects lets you make use of DateTime's advanced formatting and time difference functions. Use the "setTimestamp" function by adding the following code, where $timestamp" is your PHP time stamp:

      $date->setTimestamp($timestamp);

      A DateTime object looks similar to "2005-08-15T15:52:01+0000" or "Monday, 15-Aug-05 15:52:01 UTC."

    Difference Between Timestamps

    • Use the DateTime's "diff" function to calculate the difference between two time stamps that have been converted into DateTime objects. For example:

      $difference = $date1->diff($date2);

      "$date1" and $date2" are your DateTime objects. The returned DateInterval object has fields that give the number of years, months, days, hours, minutes and seconds between the two dates.

    Formatting the Difference Between Time Stamps

    • Format the time difference between two time stamps that have been converted into DateTime objects with the "format" function, by adding the code:

      $difference_format = $difference->format('%y-%m-%d %h-%i-%s');

      This will give you the difference in "years-months-days hours-minutes-seconds." You can output this with the code "echo $diff_format;."

Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.