Home > Article > Backend Development > Convert timestamps saved in database to past time format
This function is generally used to display the publication time of articles on Weibo and blogs. For example: If a Weibo post is posted on Sina Weibo, if it was posted today, it will display XX seconds and XX hours ago instead of the specific time. If you repost a previously published Weibo, the original Weibo will display the time it was posted.
So how to achieve it? The code is as follows:
<code><span>/**格式化时间函数 *<span> @param</span> $time 需要格式化的时间戳 */</span><span><span>function</span><span>time_format</span><span>(<span>$time</span>)</span> {</span><span>$now</span> = time(); <span>$tody</span> = strtotime(date(<span>'Y-m-d'</span>)); <span>$diff</span> = <span>$now</span> - <span>$time</span>; <span>$str</span> = <span>''</span>; <span>switch</span> (<span>$time</span>) { <span>case</span><span>$diff</span> < <span>60</span>: <span>$str</span> = <span>$diff</span> . <span>'秒前'</span>; <span>break</span>; <span>case</span><span>$diff</span> < <span>3600</span>: <span>$str</span> = floor(<span>$diff</span> / <span>60</span>) . <span>'分钟前'</span>; <span>break</span>; <span>case</span><span>$diff</span> < (<span>3600</span> * <span>8</span>): <span>$str</span> = floor(<span>$diff</span> / <span>3600</span>) . <span>'小时前'</span>; <span>break</span>; <span>case</span><span>$time</span> > <span>$tody</span>: <span>$str</span> = <span>'今天'</span> . date(<span>'Y-m-d H:i:s'</span>, <span>$time</span>); <span>break</span>; <span>default</span>: <span>$str</span> = date(<span>'Y-m-d H:i:s'</span>, <span>$time</span>); } <span>return</span><span>$str</span>; } <span>$time</span> = <span>1423110837</span>;<span>//模拟保存在数据库中的时间戳</span><span>echo</span> time_format(<span>$time</span>);</code>
Interpretation:
1. First we need to get the current time:
3. Get the difference between the timestamp in the database and the current time. That is:
4. Use switch to determine the timestamp in the database to display the corresponding time format (hour, minute, second, specific time)
The above introduces the conversion of timestamps saved in the database into past time format, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.