Time ago PHP function
Like most social networks today, instead of displaying the exact date for a post they use a time ago time format. I find it very practical. That helps the user get the information with no need to deal with different date and time formats.
You can add the following 2 functions to your php class file and call the function ago when needed. While calling the function make sure the parameter you’re passing is converted to a date object.
You may use something like this:
1 |
echo $this->ago(date_create($my_date_string)); |
Time ago PHP function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public function plural( $count, $text ) { return $count . ( ( $count == 1 ) ? ( " $text" ) : ( " ${text}s" ) ); } public function ago( $datetime ) { $interval = date_create('now')->diff( $datetime ); $suffix = ( $interval->invert ? ' ago' : '' ); if ( $v = $interval->y >= 1 ) return $this->plural( $interval->y, 'year' ) . $suffix; if ( $v = $interval->m >= 1 ) return $this->plural( $interval->m, 'month' ) . $suffix; if ( $v = $interval->d >= 1 ) return $this->plural( $interval->d, 'day' ) . $suffix; if ( $v = $interval->h >= 1 ) return $this->plural( $interval->h, 'hour' ) . $suffix; if ( $v = $interval->i >= 1 ) return $this->plural( $interval->i, 'minute' ) . $suffix; return $this->plural( $interval->s, 'second' ) . $suffix; } |
Quick Tips:
If you are using a framework like CakePHP you should probably add the time ago PHP functions to your AppController file so you can access it from any other controller.
For WordPress developers, it already has that time ago function which can be used in your theme or plugin. Here is an example for showing the time difference between the time a comment was posted and the current time:
1 2 3 |
<?php echo human_time_diff( get_comment_time('U'), current_time('timestamp') ) . ' ago'; ?> |
You can read more about it here
This is not the unique solution to do the time ago in PHP, let me know in the comments sections if you have a better way.