kreativan
2/22/2018 - 1:10 PM

Time Ago

Time ago php function

<?php

/**
 *  Time Ago
 *  @param some date
 *  @example timeAgo(@time_stamp);
 *  @example timeAgo(2019-05-01 00:22:35);
 *  @example timeAgo('2019-05-01 00:22:35', true);
 *
 */
function timeAgo($datetime, $full = false) {

    $now = new \DateTime;
    $ago = new \DateTime($datetime);
    $diff = $now->diff($ago);
    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;
    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }
    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';

}