All the time in the project was shown as 2014-10-20 10:22 and it looked stiff. In the microblogging, QQ space and other sites are usually displayed for a few seconds ago, a few minutes ago, a few hours ago, such as easy to read time, we call it a friendly time format. So how do you do it with PHP?
The general idea is as follows:
If it is cross-year and is greater than 3 days, it is displayed for a specific time
If it's Today's
If it's a minute, it's a few seconds ago.
If it's within an hour, it shows a few minutes ago.
If it is the same day and is greater than one hour, it will be displayed a few hours ago
If it was yesterday, what time did it show yesterday?
If it was the day before yesterday, what time did you see
If it is greater than three days (no cross-year), the number of months is displayed
According to the above ideas, it is not difficult to write the implementation code:
The implementation code is as follows:
Copy the Code code as follows:
Format 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 more than 30 days is not necessarily accurate, but 30 days is accurate, because one months may be 30 days may also be 31 days
$days = ($TODAYARR [0]-$dayArr [0]) *365+ (($todayArr [1]-$DAYARR [1]) *30) + ($TODAYARR [2]-$DAYARR [2]);
Number of seconds to distance
$secs = $now-$time;
if ($todayArr [0]-$dayArr [0]>0 && $days >3) {//cross-year and more than 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) {///day before yesterday
$hour =date (' h ', $time);
Return "the day before yesterday." $hour. ' Point ';
}else{//three days ago
Return date (' m-month d ', $time);
}
}
}
For reference only, please criticize or provide a better method.