time ago function in php example

90

This PHP tutorial is for converting given date into a time ago string like 2 hours age, 3 years ago. In a previous tutorial, we have seen date format conversion by using PHP inbuilt functions. In this example, we are having a custom function to change a date format into time ago string.

HTML Date Input

This HTML will show a form with a date field to get a date from the user.

PHP Custom Time Ago Function

This PHP code reads the value of the date field on form post. This value will be passed as an argument to the custom timeago() function.

In timeago() function the given date is converted into timestamp using PHP built-in strtotime(). And, this timestamp is subtracted from the current timestamp to calculate elapsed time.

The time elapsed from the given date till now is used to calculate the time ago string. The code is,

 

Leave A Reply

Your email address will not be published.