Home >Backend Development >PHP Tutorial >PHP implements timeline function (personalized time)

PHP implements timeline function (personalized time)

巴扎黑
巴扎黑Original
2016-11-11 15:04:161805browse

When we post or comment on the forum, or use QQ space to publish logs or Weibo comments, we will see that the time after the published content is displayed as "just now", "5 minutes ago", and "yesterday 10:23" etc. instead of directly displaying the specific date and 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.
Application example:
date("Y-m-d H:i:s",time());
Format the current time, output: 2010-10-11 05:27:35
strtotime(): Convert the date of any English text Time descriptions resolve to Unix timestamps.
Application example:
echo strtotime("+1 day"), "n";
Output the timestamp 1 day ago: 1286861475
date_default_timezone_set(): Set the default time zone to be used.
Generally we set 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, get a difference, and then The difference is compared with the time range (converted into seconds), and different results are output according to the range of the time axis (for example: 5 minutes ago). For ease of calculation, we convert the times into Unix timestamps.
function tranTime($time) {
$rtime = date("m-d H:i",$time);
$htime = date("H:i",$time);

$time = time() - $time;

if ($time $str = 'just';
}
elseif ($time $min = floor($time/60);
$str = $min.'minutes ago';
}
elseif ($time           $h = floor($time/(60*60));
        $str = $h.'hours ago' .$htime;
}
elseif ($time           $d = floor($time/(60*60*24));
                                     str = 'yesterday'.$rtime;
                                                                                                                  str              in tranTime() The parameter $time must be a Unix timestamp. If not, please use strtotime() to convert it to a Unix timestamp first. The above code is easy to understand at a glance, so there is no need to elaborate further.
Call the function and output directly:
$times="1286861696 ";
echo tranTime($times);

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn