php显示文章 几分钟前,几小时前,几天前发布类

文章发表时的UNIX时间戳,来转化为例如,几分钟前,几小时前,几天前....这样的提示,如微博,这看起来更加人性化,类代码如下:

  1. <?php
  2. class timeAgo
  3. {
  4. static $timeagoObject;
  5. private $rustle;
  6. private $unit;
  7. private function __construct()
  8. {
  9. }
  10. private function __clone(){ }
  11. public static function getObject()
  12. {
  13. if(! (self::$timeagoObject instanceof self) )
  14. self::$timeagoObject = new timeAgo();
  15. return self::$timeagoObject;
  16. }
  17. private function count_int($unix_C) // main function
  18. {
  19. if(! (isset($unix_C) || is_numeric($unix_C)) )
  20. return 'don't find parameter';
  21. $d = time()-$unix_C ; // $d - unix time difference value
  22. $d_int =(int)floor($d/60) ; // minimum unit -- minutes unix/60
  23. $this->unit = 0 ; // is minutes,hour or day?
  24. if($d_int < 60){ // minutes in one hour 3600
  25. $this->rustle = $d_int;
  26. $this->unit = 1;
  27. }
  28. else if($d_int < 720){ //hour in one day 3600*12
  29. $this->rustle = floor($d_int/60);
  30. $this->unit = 2 ;
  31. }
  32. else if($d_int < 7200){ //day in ten days 3600*12*10
  33. $this->rustle = floor($d_int/720);
  34. $this->unit = 3 ;
  35. }
  36. else{
  37. $this->rustle = $d ;
  38. $this->unit = 4 ;
  39. }
  40. }
  41. public function piece_str($C)
  42. {
  43. $this->count_int($C);
  44. $u = '';
  45. switch( $this->unit )
  46. {
  47. case 1:
  48. $u = 'minute';
  49. break;
  50. case 2:
  51. $u = 'hour';
  52. break;
  53. case 3:
  54. $u = 'day';
  55. break;
  56. case 4:
  57. $u = '';
  58. break;
  59. case 0:
  60. return 'sorry , get time is fail';
  61. }
  62. if($this->unit < 4)
  63. {
  64. if($this->rustle > 1)
  65. return (string)$this->rustle.$u.'s ago';
  66. else if($this->rustle == 1)
  67. return (string)$this->rustle.$u.'ago';
  68. else
  69. return 'Just now';
  70. }
  71. }
  72. /* example: $ago = timeAgo::getObject();
  73. * echo $ago->piece_str($unix);
  74. * // 2 days ago
  75. */
  76. }
  77. ?>