reenadak icon

2018-10-14_time ago_function

reenadak | PRO | 02/20/18 06:46:24 PM UTC | 0 ⭐ | 384 👁️ | Never ⏰ | []
PHP |

1.24 KB

|

None

|

0 👍

/

0 👎

    /*
    - Time Ago (Unix)
    - Converts unix time into the human readable "x seconds/minutes/hours
      /days/weeks/months/years ago/into the future" format
    
    $unixTime     - The time to turn into the "x time ago" format, 
                    can be generated with PHP's time() function which 
                    is the number of seconds that passed since Jan 1 1970.
    */
    
function str_time_ago( $val )
{
    if($val==0) return 0; // solution for zero date
    $diff = time() - strtotime($val) -(12.5*3600); // last figure is adhoc adjustment for timezone.
 
    if( $diff < 1 ) { return 'Just now or error'; }
 
    $condition = array(
        365.25 * 24 * 60 * 60  =>  'year',
        30 * 24 * 60 * 60      =>  'month',
        7 * 24 * 60 * 60       =>  'week',
        24 * 60 * 60           =>  'day',
        60 * 60                =>  'hour',
        60                     =>  'minute',
        1                      =>  'second'
    );
 
    foreach( $condition as $secs => $str )
    {
        $d = $diff / $secs;
 
        if( $d >= 1 )
        {
            $t = round( $d );
            return $t . ' ' . $str . ( $t > 1 ? 's' : '' ) . ' ago';
        }
    }
}
 
// Usage
<td class="col-md-2"><?php echo str_time_ago($row['created_at']); ?> </td>

Comments