PHP CodeBase: Detail method showing time as' just ''n minutes' and hours ago '

  • 2020-06-07 04:04:59
  • OfStack

In many cases, in order to show the timeliness of information, 1 will generally display the time as "just now", "5 minutes ago", "3 hours ago", etc., instead of printing the time directly. Like Weibo, SNS apps use this feature the most. The time format typically stored in the database is Unix timestamp, so an PHP function that converts the Unix timestamp into a timeline display is recorded here.
The function is relatively simple, it is easy to understand the code directly.

<?php
date_default_timezone_set('PRC');
$date = "1351836000";
echo tranTime($date);
function transfer_time($time)
{
    $rtime = date("m-d H:i",$time);
    $htime = date("H:i",$time);
    $time = time() - $time;
    if ($time < 60)
    {
        $str = ' just ';
    }
    elseif ($time < 60 * 60)
    {
        $min = floor($time/60);
        $str = $min.' Minutes ago ';
    }
    elseif ($time < 60 * 60 * 24)
    {
        $h = floor($time/(60*60));
        $str = $h.' Hours before  '.$htime;
    }
    elseif ($time < 60 * 60 * 24 * 3)
    {
        $d = floor($time/(60*60*24));
        if($d==1)
            $str = ' Yesterday,  '.$rtime;
        else
            $str = ' The day before yesterday  '.$rtime;
    }
    else
    {
        $str = $rtime;
    }
    return $str;
}
?>

Note that the argument $time in the function transfer_time() must be an Unix timestamp. If not, convert it to an Unix timestamp with strtotime() first

Related articles: