getButterfly Logo getButterfly code wrangling since 2005

One of the latest features I’ve added to my sports fishing portal was the nice date feature. Instead of showing PHP formatted date and time, I wanted to display time since the action took place, like “4 hours ago”, “2 days ago”, “1 minute ago” and so on.

function nicetime($date) {
if(empty($date)) {
return “ERROR: No date provided”;
$periods = array(“second”, “minute”, “hour”, “day”, “week”, “month”, “year”, “decade”);
$lengths = array(“60″,”60″,”24″,”7″,”4.35″,”12″,”10”);
$now = time();
$unix_date = strtotime($date);
// check validity of date
if(empty($unix_date)) {
return “ERROR: Invalid date”;
// is it future date or past date
if($now > $unix_date) {
$difference = $now – $unix_date;
$tense = “ago”;
else {
$difference = $unix_date – $now;
$tense = “from now”;
for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
$difference /= $lengths[$j];
$difference = round($difference);
if($difference != 1) {
// $periods[$j] .= “s”; // plural for English language
$periods = array(“seconds”, “minutes”, “hours”, “days”, “weeks”, “months”, “years”, “decades”); // plural for international words
return “$difference $periods[$j] {$tense}”;

Use <?php echo nicetime($date);?> to call the function, where $date is a variable holding your desired date, properly formatted  in PHP/MySQL. You can also pass a date directly using the standard format – date(‘Y-m-d G:i:s’), but for obvious reasons it’s better to prior assign it to a fixed variable.

Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.

If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

Leave a reply

Love programming?

Learn about the most amazing things. Get smarter everyday!