The display is 2014-10-2010:22, which seems dull. How can we use php to implement a friendly time format? I will share with you the ideas and implementation code below.
The display is very dull at,. How can we use php to implement a friendly time format? I will share with you the ideas and implementation code below.
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:
// 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 exceeds 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]); // The number of seconds from the distance $ secs = $ now-$ time; if ($ todayArr [0]-$ dayArr [0]> 0 & $ days> 3) {// return date ('Y-m-d', $ time) beyond 3 days across the year;} 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 {// return date ('m month d ', $ time) Three days ago );}}}
,