這個功能一般用在微博、部落格的文章發佈時間顯示。例如:在新浪微博發布了一篇微博,如果是今天發布的它會顯示XX秒、XX小時前發布而不是顯示具體的時間。如果轉發一篇先前發布的微博則原微博顯示其發布的時間。
那麼如何實現呢?程式碼如下:
<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>
解讀:
1.首先我們要取得目前時間即: