human readable difference between two timestamps in php

I recently encountered a common problem in computer engineering:
Displaying the difference between two timestamps in a human
readable fashion. For example, between the second day of may
2012, 12 o' clock and the fourth day of may 2012, 14 o'clock are
50 hours difference, which renders into 2 days and 2 hours.

To achieve this in php, i have written the following function:

function dateDiff($date1, $date2) {
$seconds = abs($date1 - $date2);

$delay = array();
foreach( array( 86400, 3600, 60) as $increment) {
$difference = abs(floor($seconds / $increment));
$seconds %= $increment;
$delay[] = $difference;
}

return strtr('{days} D, {hours} H, {minutes} M', array(
'{days}' => $delay[0],
'{hours}' => $delay[1],
'{minutes}' => $delay[2]));
}


At first, we get the difference between the timestamp in
seconds. We remove the sign of that value with abs().
Then we splice the seconds through 86400, 3600 and 60, which
represents the seconds of one day, a hour and a minute, each.
At last we display the calculated values to the User.

A quick, handy solution in just a few lines. Enjoy !

6 Kommentare:

  1. Hey very interesting blog!

    My web site ... citation

    AntwortenLöschen
  2. What i don't realize is in fact how you're not actually a lot more neatly-favored than you might be right now.
    You are very intelligent. You understand thus significantly
    with regards to this matter, produced me personally consider it from
    so many numerous angles. Its like men and women are not interested until it is one thing
    to do with Woman gaga! Your individual stuffs great.
    Always handle it up!

    My web blog :: actiecode kras

    AntwortenLöschen
  3. Fantastic beat ! I would like to apprentice while you
    amend your website, how can i subscribe for a blog website?

    The account aided me a acceptable deal. I had been
    a little bit acquainted of this your broadcast offered bright clear
    concept

    my blog post commercial property

    AntwortenLöschen
  4. Your method of describing all in this article
    is really nice, all be able to easily understand it, Thanks a lot.


    Also visit my web site ... citation

    AntwortenLöschen
  5. It is the best time to make some plans for the future
    and it is time to be happy. I have read this post and if I could I want to
    suggest you few interesting things or tips. Maybe you could
    write next articles referring to this article. I want to read even more things about it!


    my weblog :: Buy Bungalow

    AntwortenLöschen
  6. There is definately a lot to find out about this topic.

    I love all of the points you have made.

    Also visit my weblog: rent house

    AntwortenLöschen