Php timestamp format display friendly time function sharing, php function sharing
The time displayed in the project is, which seems dull. Websites such as Weibo and QQ space are usually displayed in a friendly time format that is a few seconds ago, a few minutes ago, or a few hours ago. So how can we implement it using php?
The general idea is as follows:
If it is a new year and more than 3 days, it is displayed as a specific time
If it is today's
If it is within one minute, it is displayed a few seconds ago.
If it is within one hour, it will be displayed several minutes ago
If it is the same day and more than one hour, it is displayed as a few hours ago
If it was yesterday, it is displayed as the time of yesterday
If it is the day before yesterday, it is displayed as the day before yesterday
If it is more than three days (not cross-year), it is displayed as the number of months
Based on the above ideas, it is not difficult to write the implementation code:
The implementation code is as follows:
Copy codeThe Code is as follows:
// Format the 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 );
// The number of days in the distance. This method is not necessarily accurate if it is more than 30 days, but it is accurate within 30 days, because a month may be 30 days or 31 days.
$ Days = ($ todayArr [0]-$ dayArr [0]) * 365 + ($ todayArr [1]-$ dayArr [1]) * 30) + ($ todayArr [2]-$ dayArr [2]);
// Number of seconds
$ Secs = $ now-$ time;
If ($ todayArr [0]-$ dayArr [0]> 0 & $ days> 3) {// cross-year period 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) {// the day before yesterday
$ Hour = date ('h', $ time );
Return "the day before yesterday". $ hour. 'point ';
} Else {// three days ago
Return date ('m-d ', $ time );
}
}
}
For your reference only. You are welcome to criticize and correct or provide better methods.
The php date function can format the timestamp into 2012-5-3.
Date ('Y-n-J', time (); // The time () function generates the timestamp of the current time. you can replace it with your own timestamp.
Reference: cn2.php.net/manual/zh/function.date.php
What is the php timestamp function?
Time () Get the current Timestamp
Strtotime () to Timestamp
Date ('Y-m-d H: I: s', time () timestamp converted to time