php timestamp formatting shows friendly time function sharing

  • 2021-07-21 08:06:12
  • OfStack

In the project, the time 1 law is shown as 2014-10-20 10:22, which is very inflexible. In Weibo, QQ space and other websites, it is usually displayed as easy-to-read time such as a few seconds ago, a few minutes ago and a few hours ago, which we call friendly time format. So how to do it with php?

The general idea is as follows:

If it is New Year's Eve and more than 3 days, it will be displayed as a specific time

If it were today's

If it is within 1 minute, it will display a few seconds ago

If it is within 1 hour, it displays a few minutes ago

If it is the same day and more than 1 hour, it will be displayed as several hours ago

If it is yesterday, it will be displayed as yesterday time

If it is the day before yesterday, it will be displayed as the day before yesterday

If it is more than 3 days (no New Year's Eve), it will be displayed as the date of the month

According to the above ideas, it is not difficult to write the implementation code:

The implementation code is as follows:


// Formatted friendly display time
function formatTime($time){
    $now=time();
    $day=date('Y-m-d',$time);
    $today=date('Y-m-d');
   
    $dayArr=explode('-',$day);
    $todayArr=explode('-',$today);
   
    // Distance of days, this method exceeds 30 Heaven is not 1 It's accurate, but 30 Within days is accurate because 1 Months may be 30 The sky could be 31 Days
    $days=($todayArr[0]-$dayArr[0])*365+(($todayArr[1]-$dayArr[1])*30)+($todayArr[2]-$dayArr[2]);
    // Number of seconds of distance
    $secs=$now-$time;
   
    if($todayArr[0]-$dayArr[0]>0 && $days>3){// New Year's Eve and over 3 Days
        return date('Y-m-d',$time);
    }else{
   
        if($days<1){// Today
            if($secs<60)return $secs.' Seconds ago ';
            elseif($secs<3600)return floor($secs/60)." Minutes ago ";
            else return floor($secs/3600)." Hours ago ";
        }else if($days<2){// Yesterday
            $hour=date('h',$time);
            return " Yesterday ".$hour.' Point ';
        }elseif($days<3){// The day before yesterday
            $hour=date('h',$time);
            return " The day before yesterday ".$hour.' Point ';
        }else{//3 Days ago
            return date('m Month d No. ',$time);
        }
    }
}

For reference only, criticism and correction are welcome or better methods are provided.


Related articles: