首頁  >  文章  >  後端開發  >  php計算兩個日期間隔的年、月、週、日數的程式碼範例

php計算兩個日期間隔的年、月、週、日數的程式碼範例

WBOY
WBOY原創
2016-07-25 08:58:511360瀏覽
  1. /**

  2. * 计算两个日期间隔的年、月、周、日数
  3. * edit bbs.it-home.org
  4. */
  5. function format($a,$b){
  6. //检查两个日期大小,默认前小后大,如果前大后小则交换位置以保证前小后大
  7. if(strtotime($a)>strtotime($b)) list($a,$b)=array($b,$a);
  8. $start = strtotime($a);
  9. $stop = strtotime($b);
  10. $extend = ($stop-$start)/86400;
  11. $result['extends'] = $extend;
  12. if($extend<7){ //如果小于7天直接返回天数
  13. $result['daily'] = $extend;
  14. }elseif($extend<=31){ //小于28天则返回周数,由于闰年2月满足了
  15. if($stop==strtotime($a.'+1 month')){
  16. $result['monthly'] = 1;
  17. }else{
  18. $w = floor($extend/7);
  19. $d = ($stop-strtotime($a.'+'.$w.' week'))/86400;
  20. $result['weekly'] = $w;
  21. $result['daily'] = $d;
  22. }
  23. }else{
  24. $y= floor($extend/365);
  25. if($y>=1){ //如果超过一年
  26. $start = strtotime($a.'+'.$y.'year');
  27. $a = date('Y-m-d',$start);
  28. //判断是否真的已经有了一年了,如果没有的话就开减
  29. if($start>$stop){
  30. $a = date('Y-m-d',strtotime($a.'-1 month'));
  31. $m =11;
  32. $y--;
  33. }
  34. $extend = ($stop-strtotime($a))/86400;
  35. }
  36. if(isset($m)){
  37. $w = floor($extend/7);
  38. $d = $extend-$w*7;
  39. }else{
  40. $m = isset($m)?$m:round($extend/30);
  41. $stop>=strtotime($a.'+'.$m.'month')?$m:$m--;
  42. if($stop>=strtotime($a.'+'.$m.'month')){
  43. $d=$w=($stop-strtotime($a.'+'.$m.'month'))/86400;
  44. $w = floor($w/7);
  45. $d = $d-$w*7;
  46. }
  47. }
  48. $result['yearly'] = $y;
  49. $result['monthly'] = $m;
  50. $result['weekly'] = $w;
  51. $result['daily'] = isset($d)?$d:null;
  52. }
  53. return array_filter($result);
  54. }

  55. print_r(format('2012-10-1','2012-12-15'));

  56. ?>

复制代码

输出结果: Array([extends]=>75[monthly]=>2[weekly]=>2)

2,php 查询某天所在的周数及对应周的起始日期

  1. /**
  2. * @file
  3. * @version 1.1
  4. */
  5. //获取某个日期的 周数、周对应的开始结束时间
  6. private function getWeekStartEndDay($day)
  7. {
  8. $g = strftime("%u",strtotime($day));
  9. return array('week_num'=>strftime("%V",strtotime($day)),'week_start_day'=>strftime('%Y-%m-%d',strtotime($day)-($g-1)*86400),'week_start_day_cn'=>strftime('%Y年%m月%d日',strtotime($day)-($g-1)*86400),'week_end_day'=>strftime('%Y-%m-%d',strtotime($day) + (7-$g)*86400),'week_end_day_cn'=>strftime('%Y年%m月%d日',strtotime($day) + (7-$g)*86400));
  10. }
  11. ?>
复制代码


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn