Time Ago or Time To Go function in 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.

 

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

 

Usage examples

 

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

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

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 *

Time limit is exhausted. Please reload CAPTCHA.