PHP Date in Human Readable Form (Facebook Style)
Apr.01, 2008 in
Development
I like to display dates relative to now, aka Facebook. So instead of displaying a date in the form 3-2-2008 (which can get confusing if you are in the US/Europe etc with dates being switched) I like to show it as 2 weeks ago as this is far easier to read.
So I came accross the following function which produces these dates in PHP:
function RelativeTime($timestamp){
$difference = time() - $timestamp;
$periods = array("sec", "min", "hour", "day", "week",
"month", "years", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
if ($difference > 0) { // this was in the past
$ending = "ago";
} else { // this was in the future
$difference = -$difference;
$ending = "to go";
}
for($j = 0; $difference >= $lengths[$j]; $j++)
$difference /= $lengths[$j];
$difference = round($difference);
if($difference != 1) $periods[$j].= "s";
$text = "$difference $periods[$j] $ending";
return $text;
}
Original post is here.
Tags: Php







December 5th, 2008 at 6:51 am
Just what I was looking for. Thanks for saving me some work!
May 27th, 2009 at 7:54 am
Thanks for this post – nice one, gave me the needed inspiration for a function I was writing.
August 23rd, 2009 at 8:51 am
Hello,
Thanks for this. today I have used it. great thing indeed.