php实现的DateDiff和DateAdd时间函数代码分享

这篇文章主要介绍了php实现的DateDiff和DateAdd时间函数代码分享,DateDiff用来计算两个时间的间隔,DateAdd用来对两个时间进行相加,需要的朋友可以参考下

扩展php中的时间函数DateDiff和DateAdd

  1. function DateDiff($part, $begin, $end)
  2. {
  3. $diff = strtotime($end) - strtotime($begin);
  4. switch($part)
  5. {
  6. case "y": $retval = bcdiv($diff, (60 * 60 * 24 * 365)); break;
  7. case "m": $retval = bcdiv($diff, (60 * 60 * 24 * 30)); break;
  8. case "w": $retval = bcdiv($diff, (60 * 60 * 24 * 7)); break;
  9. case "d": $retval = bcdiv($diff, (60 * 60 * 24)); break;
  10. case "h": $retval = bcdiv($diff, (60 * 60)); break;
  11. case "n": $retval = bcdiv($diff, 60); break;
  12. case "s": $retval = $diff; break;
  13. }
  14. return $retval;
  15. }
  16. function DateAdd($part, $number, $date)
  17. {
  18. $date_array = getdate(strtotime($date));
  19. $hor = $date_array["hours"];
  20. $min = $date_array["minutes"];
  21. $sec = $date_array["seconds"];
  22. $mon = $date_array["mon"];
  23. $day = $date_array["mday"];
  24. $yar = $date_array["year"];
  25. switch($part)
  26. {
  27. case "y": $yar += $number; break;
  28. case "q": $mon += ($number * 3); break;
  29. case "m": $mon += $number; break;
  30. case "w": $day += ($number * 7); break;
  31. case "d": $day += $number; break;
  32. case "h": $hor += $number; break;
  33. case "n": $min += $number; break;
  34. case "s": $sec += $number; break;
  35. }
  36. return date("Y-m-d H:i:s", mktime($hor, $min, $sec, $mon, $day, $yar));
  37. }
  38. Function DateAdd($part, $n, $date)
  39. {
  40. switch($part)
  41. {
  42. case "y": $val = date("Y-m-d H:i:s", strtotime($date ." +$n year")); break;
  43. case "m": $val = date("Y-m-d H:i:s", strtotime($date ." +$n month")); break;
  44. case "w": $val = date("Y-m-d H:i:s", strtotime($date ." +$n week")); break;
  45. case "d": $val = date("Y-m-d H:i:s", strtotime($date ." +$n day")); break;
  46. case "h": $val = date("Y-m-d H:i:s", strtotime($date ." +$n hour")); break;
  47. case "n": $val = date("Y-m-d H:i:s", strtotime($date ." +$n minute")); break;
  48. case "s": $val = date("Y-m-d H:i:s", strtotime($date ." +$n second")); break;
  49. }
  50. return $val;
  51. }