Converting timestamp to time ago in PHP like Facebook

Converting timestamp to time ago in PHP like Facebook

This post has been viewed 161 times.

In this tutorial, we will be learning on how to convert timestamp to time ago in PHP.

Most of you have noticed that the famous social networking site Facebook uses the time ago instead of posting the original timestamp.

Time ago is calculated based on the difference between the current time and date to the actual post time and date.

We will use a PHP function that has a parameter that accepts a timestamp it will return it in time ago format based on your server time.

What you’ll need:

  • Basic PHP syntax knowledge.
  • A text editor.
  • A local or live server.

Step 1: Get a copy of the following PHP function.


The original source of the PHP function can be found on this thread. It is answered by Glavić on September 3, 2013.

The PHP function accepts any supported date and time format. It does not only return the time ago but also gave you the privilege to return the full exact time ago. You will understand this in the later part.

Step 2: Use the PHP function.

You will be able to use the function by calling the function name. This function can either accept one (1) or two (2) parameters where the first parameter must be a valid timestamp/datetime and the second one is a boolean(true/false).

Using the true on the boolean parameter makes it return the whole time ago.

Assuming that the current time and date is exactly 2018-04-13 11:46:58

That’s it if you want to change the suffixes of the numbers you can do so by editing them in the $string variable in the function above.

Don’t forget to add the word ago if you really need it.

Hello, I am a freelance website and mobile application developer. I am also the owner of this website, so if you have any projects for me you can contact me at [email protected] or use the contact page. When I’m not doing some work, I can be found watching Anime/Asian Dramas/American TV Series, playing computer games, and writing tutorials on this website. I run the program repeatedly hoping the error won’t show up next time.