In this post, I am going to describe the simple PHP function to create article post time ago function by using easy PHP codes. This utility function calculates the time differences in words. Many popular websites use this time format instead of showing the time like : 09 Nov 2014 12:20 PM they show like : 10 Minutes Ago.
Below is an example of Time Ago feature.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | function timeAgo($ptime) { $setime = time() - $ptime; if ($setime < 1) { return '0 seconds'; } $interval = array( 12 * 30 * 24 * 60 * 60 => 'year', 30 * 24 * 60 * 60 => 'month', 24 * 60 * 60 => 'day', 60 * 60 => 'hour', 60 => 'minute', 1 => 'second' ); foreach ($interval as $secs => $str) { $d = $setime / $secs; if ($d >= 1) { $r = round($d); return $r . ' ' . $str . ($r > 1 ? 's' : ''); } } } |
1 2 3 4 5 6 7 8 | $t=time()-600; echo time_ago($t); //outputs => 10 mins $t=time()-3600; echo time_ago($t); //outputs => 1 hour $t=time()-86400 * 65; echo time_ago($t); //outputs => 2 months |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | <?php // PHP program to convert timestamp // to time ago function to_time_ago( $time ) { // Calculate difference between current // time and given timestamp in seconds $diff = time() - $time; if( $diff < 1 ) { return 'less than 1 second ago'; } $time_rules = 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_rules as $secs => $str ) { $div = $diff / $secs; if( $div >= 1 ) { $t = round( $div ); return $t . ' ' . $str . ( $t > 1 ? 's' : '' ) . ' ago'; } } } // to_time_ago() function call echo to_time_ago( time() - 5); ?> |
Output
5 seconds ago
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: PHP