You need a function to publish your date like “1 hour ago”, “3 days ago” or something like that? No problem. Here is my way to do that.

function ws_format_time($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;
    $diff = (array) $diff;

    $string = [
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    ];

    foreach ($string as $key => $value) {
        if ($diff[$key]) {
            $prefix = 's';
            $string[$key] = $diff[$key] . ' ' . $value . ($diff[$key] > 1 ? $prefix : '');
        } else {
            unset($string[$key]);
        }
    }

    if (!$full) {
        $string = array_slice($string, 0, 1);
    }

    return $string ? implode(', ', $string) . ' ago' : 'just now';
}

Leave a Reply

Your email address will not be published. Required fields are marked *