PHP 

This tutorial shows how to display how much time already passed or how much time to go for a given datetime.

We have to implement this kind of functionality in many scenarios like someone has posted comment on your blog, tutorial, product or article then you want to show how much time ago that particular comment was posted. The time ago function may display the time format like – 1 sec ago, 2 secs ago, 1 min ago, 3 mins ago or 4 days ago etc.

Now we may need to display also how many seconds, minutes or even days “to go” to happen something. In real life scenarios like Pepsi IPL 15 days to go, Brasil Football World Cup 5 days to go etc.

Most of us have already seen the time ago functionality for the comment system in Facebook, Linkedin, Twitter etc..

So for this kind of message to display, we need a function which will show us the similar format for the time.

The below function takes one argument of type datetime. First the function validates whether the given datetime is in valid format or not. If the datetime format is valid then it calculates how much time has already been passed or how much time is left for a given datetime.

function time_ago($date) {
$is_valid = is_date_time_valid($date);
if ($is_valid) {
$timestamp = strtotime($date);
$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 time
$ending = "ago";
} else { // this was in the future time
$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;
}else {
return 'Date Time must be in "yyyy-mm-dd hh:mm:ss" format';
}
}

 

Below function checks whether the date time is in valid format or not

function is_date_time_valid($date) {
if (date('Y-m-d H:i:s', strtotime($date)) == $date) {
return TRUE;
} else {
return FALSE;
}
}

 

Usage examples

$date = '2014-04-10 14:20:15';
echo time_ago($date);

3 months ago

$date = '2014-07-20 14:20:15';
echo time_ago($date);

3 weeks to go

 

That’s all. Thanks for reading. Please do not forget to leave a comment.

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

3 thoughts on “Time Ago or Time To Go function in php

Leave a Reply

Your email address will not be published. Required fields are marked *