>  기사  >  백엔드 개발  >  php计算两个日期间隔的年、月、周、日数的代码示例

php计算两个日期间隔的年、月、周、日数的代码示例

WBOY
WBOY원래의
2016-07-25 08:58:511359검색
  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$result['daily'] = $extend;
  13. }elseif($extendif($stop==strtotime($a.'+1 month')){
  14. $result['monthly'] = 1;
  15. }else{
  16. $w = floor($extend/7);
  17. $d = ($stop-strtotime($a.'+'.$w.' week'))/86400;
  18. $result['weekly'] = $w;
  19. $result['daily'] = $d;
  20. }
  21. }else{
  22. $y= floor($extend/365);
  23. if($y>=1){ //如果超过一年
  24. $start = strtotime($a.'+'.$y.'year');
  25. $a = date('Y-m-d',$start);
  26. //判断是否真的已经有了一年了,如果没有的话就开减
  27. if($start>$stop){
  28. $a = date('Y-m-d',strtotime($a.'-1 month'));
  29. $m =11;
  30. $y--;
  31. }
  32. $extend = ($stop-strtotime($a))/86400;
  33. }
  34. if(isset($m)){
  35. $w = floor($extend/7);
  36. $d = $extend-$w*7;
  37. }else{
  38. $m = isset($m)?$m:round($extend/30);
  39. $stop>=strtotime($a.'+'.$m.'month')?$m:$m--;
  40. if($stop>=strtotime($a.'+'.$m.'month')){
  41. $d=$w=($stop-strtotime($a.'+'.$m.'month'))/86400;
  42. $w = floor($w/7);
  43. $d = $d-$w*7;
  44. }
  45. }
  46. $result['yearly'] = $y;
  47. $result['monthly'] = $m;
  48. $result['weekly'] = $w;
  49. $result['daily'] = isset($d)?$d:null;
  50. }
  51. return array_filter($result);
  52. }
  53. print_r(format('2012-10-1','2012-12-15'));

  54. ?>
复制代码

输出结果: 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으로 문의하세요.