Showing posts with label 1 year ago. Show all posts
Showing posts with label 1 year ago. Show all posts

Friday 17 November 2017

Converting Timestamp to time ago in PHP e.g 1 day ago, 1 year ago

Converting Timestamp to time ago in PHP e.g 1 day ago, 1 year ago

 

Hello Here Example of set up time as human readable formate in php

<?php
function time_elapsed_string($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';
}
echo date('Y-m-d H:i:s');
echo "<br/>";
echo time_elapsed_string('2017-11-17 11:36:00',true);
echo "<br/>";
echo time_elapsed_string('@1367367755'); # timestamp input
echo "<br/>";
echo time_elapsed_string('2013-05-01 00:22:35', true);
echo "<br/>";
?>