php计算时间间隔实现程序代码

在文章里面我说了很多关于php计算时间间隔实现程序代码的实现方法原理以及分析如何来做这个功能,下面实例是告诉我们在论坛有看到关于多少秒钟前发了帖子等这些功能.

分析:实际时间

  1. 30秒==60
  2. 5分钟==60*10 //这里我觉得应该是五分钟,而不是一分钟,个人觉得 一分钟的话应该是 60*2
  3. 10分钟==60*20
  4. 30分钟==60*60
  5. 1小时==60*60*2
  6. 2.5小时==60*60*5

原理:用当前时间time(),减去你信息录入时的新增时间,(注意是时间戳),然后得出的差数,就是秒数,再根据自己的需要来转换啊,例如你想转换成分钟,就除以60。

实例:代码如下

  1. <?php
  2. /**
  3. * 时间差计算
  4. *
  5. * @param Timestamp $time
  6. * @return String Time Elapsed
  7. * @author Shelley Shyan
  8. * @copyright http://www.phpfensi.com (Professional PHP Architecture)
  9. */
  10. function time2Units ($time)
  11. {
  12. $year = floor($time / 60 / 60 / 24 / 365);
  13. $time -= $year * 60 * 60 * 24 * 365;
  14. $month = floor($time / 60 / 60 / 24 / 30);
  15. $time -= $month * 60 * 60 * 24 * 30;
  16. $week = floor($time / 60 / 60 / 24 / 7);
  17. $time -= $week * 60 * 60 * 24 * 7;
  18. $day = floor($time / 60 / 60 / 24);
  19. $time -= $day * 60 * 60 * 24;
  20. $hour = floor($time / 60 / 60);
  21. $time -= $hour * 60 * 60;
  22. $minute = floor($time / 60);
  23. $time -= $minute * 60;
  24. $second = $time;
  25. $elapse = '';
  26. $unitArr = array('年' =>'year', '个月'=>'month', '周'=>'week', '天'=>'day',
  27. '小时'=>'hour', '分钟'=>'minute', '秒'=>'second'
  28. );
  29. foreach ( $unitArr as $cn => $u )
  30. {
  31. if ( $$u > 0 )
  32. {
  33. $elapse = $$u . $cn;
  34. break;
  35. }
  36. }
  37. return $elapse;
  38. }
  39. $past = 2052345678; // Some timestamp in the past
  40. $now = time(); // Current timestamp
  41. $diff = $now - $past;
  42. echo '发表于' . time2Units($diff) . '前';
  43. ?>

这是一个刚入门的同学写的,代码如下:

  1. <?php
  2. $regist1 = "05/12/2006";
  3. $regist2 = "10/05/2007";
  4. list($month1,$day1,$year1) = explode("/",$regist1);
  5. list($month2,$day2,$year2) = explode("/",$regist2);
  6. $regist1 = mktime(0,0,0,$month1,$day1,$year1);
  7. $regist2 = mktime(0,0,0,$month2,$day2,$year2);
  8. $time_difference = $regist2-$regist1;
  9. echo ("时间差:");
  10. echo date("Y",$time_difference) - 1970;
  11. echo ("年");
  12. echo date("m",$time_difference) - 1;
  13. echo ("个月");
  14. echo date("d",$time_difference) - 1;
  15. echo ("天");
  16. ?>
好了喜欢就自己选择用吧。