
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
PHP program to convert a given timestamp into time ago
To convert a given timestamp into time ago, the code is as follows −
Example
<?php function to_time_ago( $time ) { $difference = time() - $time; if( $difference < 1 ) { return 'less than only a second ago'; } $time_rule = array ( 12 * 30 * 24 * 60 * 60 => 'year', 30 * 24 * 60 * 60 => 'month', 24 * 60 * 60 => 'day', 60 * 60 => 'hour', 60 => 'minute', 1 => 'second' ); foreach( $time_rule as $sec => $my_str ) { $res = $difference / $sec; if( $res >= 1 ) { $t = round( $res ); return $t . ' ' . $my_str . ( $t > 1 ? 's' : '' ) . ' ago'; } } } echo "The timestamp to time ago conversion is "; echo to_time_ago( time() - 600); ?>
Output
The timestamp to time ago conversion is 10 minutes ago
A function named ‘to_time_ago’ is defined that checks the difference between the time passed as parameter to the function and the time function. If this difference is found to be less than 1, it returns that the time passed just a second ago. Otherwise, the year, month, day, hour, minute, and second is generated in an array. A ‘foreach’ loop is used to iterate over the array previously generated. The time difference is computed and printed on the console.
- Related Articles
- Print the time an hour ago PHP?
- Convert given time into words in C++
- How to convert a Unix timestamp to time in JavaScript?
- Pandas program to convert a string of date into time
- Python Pandas - Convert Timestamp to another time zone
- Python Pandas - Convert given Timestamp to Period
- Python Pandas - Convert naive Timestamp to local time zone
- Convert timestamp coming from SQL database to String PHP?
- Combine date and time column into a timestamp in MySQL?
- Convert MySQL timestamp to UNIX Timestamp?
- How to insert a row with a timestamp “X days ago” in MySQL?
- Convert UNIX timestamp into human readable format in MySQL?
- Python Pandas - Convert given Timestamp to Period with minutely frequency
- Python Pandas - Convert given Timestamp to Period with weekly frequency
- Python Pandas - Convert given Timestamp to Period with monthly frequency

Advertisements