PHP Smart Date Function – Display Time Elapsed (Difference) Based on a Given Timestamp

Posted in Web Development on 12 December 2011 0 comment

As a web developer, we often need to display dates in our website. As a web user myself, I don’t like to read full dates like “26 November 2011 11:30PM” because it takes me a little while to interpret the date. I prefer reading smart dates like “1 hour ago” or “6 months ago”. Therefore, here I wrote a quick and simple function in PHP that display the time difference/elapsed based on a given timestamp value.

PHP Smart Date Function

/*
Simple PHP Smart Date Function
by Zen (http://zenverse.net)
*/
function smartdate($timestamp) {
	$diff = time() - $timestamp;
 
	if ($diff <= 0) {
		return 'Now';
	}
	else if ($diff < 60) {
		return grammar_date(floor($diff), ' second(s) ago');
	}
	else if ($diff < 60*60) {
		return grammar_date(floor($diff/60), ' minute(s) ago');
	}
	else if ($diff < 60*60*24) {
		return grammar_date(floor($diff/(60*60)), ' hour(s) ago');
	}
	else if ($diff < 60*60*24*30) {
		return grammar_date(floor($diff/(60*60*24)), ' day(s) ago');
	}
	else if ($diff < 60*60*24*30*12) {
		return grammar_date(floor($diff/(60*60*24*30)), ' month(s) ago');
	}
	else {
		return grammar_date(floor($diff/(60*60*24*30*12)), ' year(s) ago');
	}
}
 
 
function grammar_date($val, $sentence) {
	if ($val > 1) {
		return $val.str_replace('(s)', 's', $sentence);
	} else {
		return $val.str_replace('(s)', '', $sentence);
	}
}

Basically I defined 2 functions above:
smartdate – calculates the difference between given timestamp and current time, then returns the correct sentence
grammar_date – modifies the returned sentence to plural form or singular form

Usage

The usage is simple and straightforward.

<?php
 
//example 1
echo smartdate($yourtimestamp);
 
//example 2
echo 'Posted on '.smartdate($yourtimestamp); 
 
?>

By default, this function returns the floor() value, i.e: instead of returning “1.7 years ago”, it returns “1 year ago”. Anyway, the function can be easily modified to suit your specific needs.

Give users the choice to view the full date

1 disadvantage of smart date is of course, it reduces the level of detail and granularity of the date information. For example, dates of 13 months ago or 19 months ago will both be displayed as “1 year ago”.

The most common way to let user view the full date is to add a “title” attribute with full date as the attribute value. Now, when user mouseover your smart date, they can see the full date popping up as tooltip. Facebook uses this approach.

<?php
 
//from example 2 above
echo 'Posted on <span title="' . $originalfulldate . '">' . smartdate($yourtimestamp) . '</span>'; 
 
?>

Hope this helps.

 

Posted by Zen on 12 December 2011 • 39,770 visits 0 comment
Tags :


or Subscribe to specific category only :




  - 0 Comments


No comment yet. Be the first to leave a comment!

Leave a Reply

You must be logged in to post a comment.

Previous Post
«
Next Post
»