I wrote an article "converting the time of a text expression to the corresponding time" to convert the time of a text description to the corresponding time. Now I want to convert the time to a text description.
After posting on Weibo or some other forums, I will see the posting time as "just", "1 minute ago", "8: 00 yesterday", rather than showing the specific date and time.
This section describes how to implement time Conversion Based on the timeline.
Time (): returns the current UNIX timestamp.
Date (): format a local time/date.
Example:
Date ("Y-m-d h: I: S", time ());
Format the current time. Output: 15:27:35
Strtotime (): parses the date and time description of any English text into a Unix timestamp.
Example:
Echo strtotime ("+ 1 day"), "\ n ";
Output The timestamp one day ago: 1294474872
Date_default_timezone_set (): sets the default time zone to use.
Generally, we set Beijing Time: date_default_timezone_set ("PRC ");
After understanding the above functions, let's write the timeline function:
The principle of this function is to compare the current system time with the target time to get a difference, and then compare the difference with the time range (converted to seconds, output different results (for example, 5 minutes ago) based on the time range in the timeline ). For ease of calculation, we convert all the time into UNIX timestamps.
1234567891011121314151617181920212223242526272829 |
Function trantime ($ time) {$ rtime = date ("M-d h: I", $ time); $ htime = date ("H: I", $ time ); $ time = Time ()-$ time; if ($ time <60) {$ STR = 'hangzhou';} elseif ($ time <60*60) {$ min = floor ($ time/60); $ STR = $ Min. 'minute ago ';} elseif ($ time <60*60*24) {$ H = floor ($ time/(60*60); $ STR = $ H. 'hour ago '. $ htime;} elseif ($ time <60*60*24*3) {$ d = floor ($ time/(60*60*24 )); if ($ d = 1) $ STR = 'Yesterday '. $ rtime; else $ STR = 'day before yesterday '. $ rtime;} else {$ STR = $ rtime;} return $ STR ;} |