Tuesday, February 26, 2013

[PHP] How to get time difference in day, hour, minute like what the facebook timestamp do?

Here's how to get the time difference between the given time and the present time.

If the time difference is not exceeding  7 DAYS, we will display time difference like
Monday at 12:30pm
Tuesday at 12:30pm
Wednesday at 12:30pm
Thursday at 12:30pm
Friday at 12:30pm
Saturday at 12:30pm
Sunday at 12:30pm
and so on...

If the time difference is not exceeding  24 HOURS, we will display time difference like
23 Hours ago
19 Hours ago
15 Hours ago
8 Hours ago
1 Hour ago
and so on...

If the time difference is not exceeding  60 MINUTES, we will display time difference like
59 minutes ago
47 minutes ago
33 minutes ago
25 minutes ago
18 minutes ago
1 minute ago
and so on...

If the time difference is not exceeding  60 SECONDS, we will display time difference like
59 seconds ago
47 seconds ago
33 seconds ago
25 seconds ago
18 seconds ago
1 second ago
and so on...


So here is the  code

<?php

//$sample_date came from profile.php

$now = date('Y-m-d H:i:s');

$sample_date = "2013-02-23 17:30:25";        //year-month-day hour:minute:second

$start_date = new DateTime($sample_date);

$since_start = $start_date->diff(new DateTime($now));

$year = $since_start->y;

$month = $since_start->m;

$day = $since_start->d;

$hour = $since_start->h;

$minute = $since_start->i;

$second = $since_start->s;

$date = strtotime($sample_date);

$time = date("g:ia", strtotime($sample_date));

if($day != 0)

{

    if($day == 1)        //yesterday

    {     

        $displayDate = "Yesterday at $time";

    }

    else if(($day > 1) && ($day < 8))        //day of the week

    {     

        $displayDate = date('l', $date) . " at $time";

    }

    else        //month

    {

        $yearAppend = (date('Y', $date) != date('Y'))? ", " . date('Y', $date) : "";

         

        $displayDate = date('F j', $date) . $yearAppend; 

    }

}

else

{

 

     

    if($hour != 0)

    {

        $s = ($hour>1)? "s" : "";

        $displayDate = "$hour hour$s ago";

    } 

    else if($minute != 0)

    {

        $s = ($minute>1)? "s" : "";

        $displayDate = "$minute minute$s ago";

    }

    else

    {

        $s = ($second>1)? "s" : "";

        $displayDate = "$second second$s ago";

    }

}

echo "$displayDate";

?>

No comments:

Post a Comment