[Abstract] The comment time of the topic comment template is in the form of a timeline, that is, X hours and X days ago. However, it is found that some comments are displayed two years ago when the date is less than two years ago.
The comment time of the topic comment template is in the form of a timeline, that is, X hours and X days ago. However, it is found that some comment dates are two years ago, but not two years ago, as shown in the following figure.
So we checked the source code,
function timeago( $ptime ) { $ptime = strtotime($ptime); $etime = time() - $ptime; If ($etime<1) return 'Just'; $interval = array ( 12 * 30 * 24 * 60 * 60=>'. date ('Y-m-d', $ptime). ')', 30 * 24 * 60 * 60=>'months ago ('. date ('m-d ', $ptime).') ', 7 * 24 * 60 * 60=>'. date ('m-d', $ptime). ')', 24 * 60 * 60=>'days ago', 60 * 60=>'hours ago', 60=>'minutes ago', 1=>'seconds ago' ); foreach ($interval as $secs => $str) { $d = $etime / $secs; if ($d >= 1) { $r = round($d); return $r . $str; } }; }
It can be seen that the logic of the source code is to determine the difference between the current timestamp and the comment timestamp. Then the specific values and units are displayed by rounding through function calculation.
1. <1 second shows just
2. >1s and<60s display X seconds ago
3. >60 seconds and<60 * 60 seconds display X minutes ago
...
At this time, a function is found $r = round($d);
This is the rounding method, which is why, for example, the above figure shows two years when the date is less than two years, because the date difference is actually 1.991 years. Although it is less than two years, it is rounded to two years.
So if you want to display the timeline in a more friendly way, it is better to remove the decimal directly, as long as the integer part, then $r = round($d);
Change to $r = intval($d);
A friendly timeline is displayed, which is one year ago.
However, there is another problem at this time. Although the week, day, hour, minute and second are accurate, the number of days in each month is not fixed at 30 days, and the number of days in a year is more than 12 * 30=360 days, which may lead to a month being displayed before the comment date reaches 31 days.
Therefore, it is necessary to directly change the number of years from 30 * 12 to 365. Although it is impossible to take leap years into account, it is not satisfactory; The same is true for months. You can only write 30 for most months.
This article was last updated on September 5, 2019, and has not been updated for more than one year. If the article content or picture resources are invalid, please leave a message for feedback, and we will deal with it in a timely manner, thank you!