温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

php如何取出一个时间段内每个月的开始时间和结束时间存入到数组中

发布时间:2021-10-21 09:40:57 来源:亿速云 阅读:104 作者:小新 栏目:web开发

这篇文章主要为大家展示了“php如何取出一个时间段内每个月的开始时间和结束时间存入到数组中”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“php如何取出一个时间段内每个月的开始时间和结束时间存入到数组中”这篇文章吧。

要求:如果时间段的开始时间大于每个月的1号,则把时间段的开始时间存入到数组中,反之,则把1号存入到数组中,如果时间段的结束时间大于每个月的最后一天,则把时间段的结束时间存入到数组中,反之,则把每个月的最后一天存入到数组中

注意:如果是整月,则设置falg字段标志

<?php
 date_default_timezone_set('PRC');
//获取一个月的的结束时间和开始时间
function get_monthinfo_by_date($date){
    $ret = array();
    $timestamp = strtotime($date);
    $mdays = date('t', $timestamp);
    return array(
      'month_start_day' => date('Y-m-1', $timestamp),
      'month_end_day' => date('Y-m-'.$mdays, $timestamp)
      );
  }

function get_months($sdate, $edate) {
    $range_arr = array();
    $one_date=$sdate;//$sdate会不断变化,但是需要使用到第一次的$sdate值,
    do {
        
      $monthinfo = get_monthinfo_by_date($sdate);
      $end_day = $monthinfo['month_end_day'];
    
      $tmp=array();
     
      //把开始时间和每个月的1号相比,如果开始时间大于1个月的1号,则把开始时间放入到数组中,反之,则把1个月的1号放入到数组中
      if(strtotime($one_date)>strtotime($monthinfo['month_start_day']))
      {
         $tmp['SD'] = $one_date;
         
         
      }else
      {
          $tmp['SD'] = $monthinfo['month_start_day'];
        
            $tmp['Flag'] =date('Ym00000000',strtotime($monthinfo['month_start_day']));
        
      }
      
       //把结束时间和每个月的最后一天相比,如果结束时间大于一个月的最后一天,则把结束时间放入到数组中,反之,则把一个月的最后一天放入到数组中
      if( strtotime($edate)>strtotime($monthinfo['month_end_day']))
      {
          $tmp['ED']=$end_day;
          
      }else
      {
          $tmp['ED']=$edate;
          if(strtotime($edate)!=strtotime($monthinfo['month_end_day']))
          {
            unset($tmp['Flag']);//开始时间里面设置了$tmp['Flag'],如果最后一个月的最后一天和时间段的结束时间不一样,就删除这个$tmp['Flag']
          }
      }
        array_push($range_arr,$tmp);
        //下一个月
       $sdate = date('Y-m-d', strtotime($sdate.'+1 month'));
    
    }while($end_day < $edate);
    return $range_arr;
  }
echo "<pre>";
print_r(get_months('2014-02-05', '2014-04-30'));
echo "</pre>";

结果如下

Array
(
    [0] => Array
        (
            [SD] => 20140205
            [ED] => 20140228
        )

    [1] => Array
        (
            [SD] => 20140301
            [Flag] => 20140300000000
            [ED] => 20140331
        )

    [2] => Array
        (
            [SD] => 20140401
            [Flag] => 20140400000000
            [ED] => 20140430
        )

)

以上是“php如何取出一个时间段内每个月的开始时间和结束时间存入到数组中”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI