PHP implements the timeline function code. This article describes how to implement time conversion based on the timeline. First, we need to understand several functions of time: time (): return the current Unix timestamp date (): format a local time/this article will introduce how to implement time conversion based on the timeline.
First, we need to understand several functions of time:
Time (): returns the current Unix timestamp.
Date (): format a local time/date.
Example:
The code is as follows:
Date ("Y-m-d H: I: s", time (); // format the current time. output: 07:27:35
Strtotime (): parses the date and time description of any English text into a Unix timestamp.
Example:
The code is as follows:
Echo strtotime ("+ 1 day"), "\ n"; // output the timestamp one day ago: 1316932222
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.
The code is as follows:
Function tranTime ($ time ){
$ Rtime = date ("m-d H: I", $ time );
$ Htime = date ("H: I", $ time );
$ Time = time ()-$ time;
If ($ time <60 ){
$ Str = 'gang ';
}
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 before '. $ htime;
}
Elseif ($ time <60*60*24*3 ){
$ D = floor ($ time/(60*60*24 ));
If ($ d = 1)
$ Str = 'Yesterday '. $ rtime;
Else
$ Str = 'day before Day'. $ rtime;
}
Else {
$ Str = $ rtime;
}
Return $ str;
}
The $ time parameter in the tranTime () function must be a Unix Timestamp. if not, use strtotime () to convert it to a Unix timestamp. The above code is clear at a glance, and you don't need to talk about it more.
Call the function and directly output the following:
The code is as follows:
$ Times = "1316932222 ";
Echo tranTime ($ times );
Bytes. First, we need to understand several functions of time: time (): return the current Unix timestamp date (): format a local time /...