PHP 將時間顯示為“剛剛”“n分鐘/小時前”等

來源:互聯網
上載者:User
在很多場合為了顯示出資訊的及時性,一般會將時間顯示成“剛剛”,“5分鐘前”,“3小時前”等,而不是直接將時間列印出來。比如微博,SNS類應用就最 長用到這個功能。而一般儲存在資料庫中的時間格式為 Unix時間戳記,所以這裡記錄一個將 Unix時間戳記 轉化為時間軸顯示的PHP函數。
  1. date_default_timezone_set('PRC');
  2. $date = "1351836000";
  3. echo tranTime($date);
  4. function transfer_time($time)
  5. {
  6. $rtime = date("m-d H:i",$time);
  7. $htime = date("H:i",$time);
  8. $time = time() - $time;
  9. if ($time < 60)
  10. {
  11. $str = '剛剛';
  12. }
  13. elseif ($time < 60 * 60)
  14. {
  15. $min = floor($time/60);
  16. $str = $min.'分鐘前';
  17. }
  18. elseif ($time < 60 * 60 * 24)
  19. {
  20. $h = floor($time/(60*60));
  21. $str = $h.'小時前 '.$htime;
  22. }
  23. elseif ($time < 60 * 60 * 24 * 3)
  24. {
  25. $d = floor($time/(60*60*24));
  26. if($d==1)
  27. $str = '昨天 '.$rtime;
  28. else
  29. $str = '前天 '.$rtime;
  30. }
  31. else
  32. {
  33. $str = $rtime;
  34. }
  35. return $str;
  36. }
  37. ?>
複製代碼
PHP
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.