This article will describe how to implement a time conversion based on the timeline.
First we need to understand several functions of time:
Time (): Returns the current Unix timestamp
Date (): Formats a local time/date.
Application Examples:
Copy Code code as follows:
Date ("Y-m-d h:i:s", Time ()); Format current time, output: 2011-9-24 07:27:35
Strtotime (): Resolves a date-time description of any English text to a Unix timestamp.
Application Examples:
Copy Code code as follows:
Echo strtotime ("+1 Day"), "\ n"; Output timestamp 1 days ago: 1316932222
Date_default_timezone_set (): Sets the default time zone to use.
Generally we set up Beijing time: Date_default_timezone_set ("PRC");
After understanding the above functions, we write the timeline function:
The principle of this function is to compare the current time of the system with the target time, to get a difference, and then compare the difference with the time range (converted to seconds), according to its output in the time axis different results (such as: 5 minutes ago). For ease of calculation, we convert the time to a UNIX timestamp.
Copy Code code as follows:
function Trantime ($time) {
$rtime = Date ("m-d h:i", $time);
$htime = Date ("H:i", $time);
$time = Time ()-$time;
if ($time < 60) {
$str = ' just ';
}
ElseIf ($time < 60 * 60) {
$min = Floor ($time/60);
$str = $min. ' Minutes 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;
}
The parameter $time in the function trantime () must be a Unix timestamp, and if not, convert it to a UNIX timestamp using Strtotime (). The above code at a glance to understand, no more.
Call function, Direct output:
Copy Code code as follows:
$times = "1316932222";
echo Trantime ($times);