代码之家  ›  专栏  ›  技术社区  ›  ggutenberg

返回介于开始日期和结束日期之间(含)的月份数组

  •  2
  • ggutenberg  · 技术社区  · 16 年前

    $start = strtotime('2010-08-20');
    $end = strtotime('2010-09-15');
    $month = $start;
    while($month <= $end) {
      $months[] = date('Y-m', $month);
      $month = strtotime("+1 month", $month);
    }
    

    问题是,在上面的示例中,它只向数组中添加了“2010-08”,而没有添加“2010-09”。我觉得解决办法应该是显而易见的,但我就是看不出来。

    请注意,这应考虑以下情况:

    $start = strtotime('2010-08-20');
    $end = strtotime('2010-08-21');
    // should return '2010-08'
    
    $start = strtotime('2010-08-20');
    $end = strtotime('2010-09-01');
    // should return '2010-08,2010-09'
    
    $start = strtotime('2010-08-20');
    $end = strtotime('2010-10-21');
    // should return '2010-08,2010-09,2010-10'
    

    另外,我的主机上的PHP版本是5.2.6,所以它必须在这些限制范围内工作。


    我使用的解决方案是基于下面的答案。设置 $start 一个月的第一天。然而,我不能让它只与工作 strtotime() 相反,我不得不使用我在网上找到的另一个功能。

    function firstDayOfMonth($uts=null) 
    { 
        $today = is_null($uts) ? getDate() : getDate($uts); 
        $first_day = getdate(mktime(0,0,0,$today['mon'],1,$today['year'])); 
        return $first_day[0]; 
    }
    
    $start = strtotime('2010-08-20');
    $end = strtotime('2010-09-15');
    $month = firstDayOfMonth($start);
    while($month <= $end) {
      $months[] = date('Y-m', $month);
      $month = strtotime("+1 month", $month);
    }
    
    3 回复  |  直到 16 年前
        1
  •  2
  •   cichy    16 年前

    问题是$start-day大于end-day,因此在您添加月份以开始其大于end之后,解决方案是使用月份的第一天,如2010-08-01,因此在您添加+1个月之后,您将获得至少相等的$end;)

        2
  •  0
  •   Centurion    16 年前

    $start = strtotime('2010-08-20');
    $end = strtotime('2010-10-15');
    $month = $start;
    $months[] = date('Y-m', $start);
    while($month <= $end) {
      $month = strtotime("+1 month", $month);
      $months[] = date('Y-m', $month);
    }
    
        3
  •  0
  •   rubber boots    16 年前

    添加

    if( date('d',$month) != date('d',$end) )
       $months[] = date('Y-m', $month);
    

    在回路下面。这意味着,你加上最后一个 如果它只是部分包含在 $end

    rbo公司