Discuz教程网

PHP中将时间差转换为字符串提示的实现代码

[复制链接]
authicon dly 发表于 2011-9-2 21:43:26 | 显示全部楼层 |阅读模式
如微博

这看起来更加人性化,好吧,上代码
代码如下:

  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. ?>
复制代码








上一篇:PHP数据结构 算法(PHP描述) 简单选择排序 simple selection sort
下一篇:Discuz X2 在线音乐 (盒)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

1314学习网 ( 浙ICP备10214163号 )

GMT+8, 2025-5-2 18:17

Powered by Discuz! X3.4

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表