获取两个给定日期之间的年份和月份列表的微妙方法


delicate way to get a list of years and month between two given dates

>我想获取两个给定日期之间的年份和月份列表

这是我的代码

    function yearMonth($start_date, $end_date)  
    {  
        $years = array();
        $base  = 0 ;
        while(($start_date) < $end_date)
        {
                $y           = date('Y' , $start_date);
                // if its the original start_time check the month from 
                //current date else get the first day and month in that year
                $base        = ($base == 0 )  ? $start_date : strtotime("{$y}-1-1"); 
                for($i = 1 ; $i <= 12 ; $i++ )
                {
                   if($base > $end_date)
                   break;
                   $years[date("Y", $start_date)][] = date("F" , $base); 
                   $base += 2629743.83;
                }
               $base += $start_date += 31556926 ;

        }
        return $years;
    }  
    $list  =  yearMonth(strtotime("2010-11-8") , strtotime("2012-11-11") );  
    var_dump($list);

所以这就是问题所在

$base     = ($base == 0 )  ? $start_date : strtotime("{$y}-1-1"); 

在这里,我检查start_date是否是我传递给函数的原始文件如果是,我设置了查找该年月份等于start_date的基础如果不是原件,我将基数设置为等于当年的第一个月

现在我们到了我的问题

for($i = 1 ; $i <= 12 ; $i++ )

在这里,我假设那一年有 12 个月,但如果它是原始start_date它可能会更少

如何计算给定日期年份的剩余月份?

另一个问题就在这里

            for($i = 1 ; $i <= 12 ; $i++ )
            {
                   if($base > $end_date)
                   break;
                   $years[date("Y", $start_date)][] = date("F" , $base); 
                   $base += 2629743.83;
            }

所以我认为每个月都有 2629743.83 秒,但由于闰年的原因,它不是很准确

有没有更清洁的方法可以做到这一点?

我有两种解决方案,要么改变你现有的代码,要么使用 PHP 的内置 DateTime 类。

您希望在代码中修复两件事:

  • 仅列出起始年份的剩余月份 - 您可以通过添加检查$base日期是否在您输出的年份来执行此操作。
  • 在每年数组中获取正确的月份 - 我们可以通过将$base增加每个月的正确天数来做到这一点。我们可以通过以下方式获取一个月中的天数 date('t') .
for($i = 1 ; $i <= 12 ; $i++ )
{
   if($base > $end_date)
   break;
   $base_year = date('Y', $base);
   if ($base_year == $y) {
    $years[date("Y", $start_date)][] = date("F" , $base); 
    $base += 60*60*24*date('t', strtotime($base_year.'-'.$i."-1")); 
   }
}

或者,可以使用 DateTime 对象简化代码。此示例基于 DatePeriod 注释中的一些代码。

注意:函数的参数不需要用strtotime解析的日期。

function yearMonth($start_date, $end_date) 
{
    $begin = new DateTime( $start_date );
    $end = new DateTime( $end_date);
    $interval = new DateInterval('P1M'); // 1 month interval
    $period = new DatePeriod($begin, $interval, $end);
    foreach ( $period as $dt )
        $years[$dt->format( "Y" )][] = $dt->format( "F" );
    return $years;
}
$list  =  yearMonth("2010-11-8", "2012-11-11");  
var_dump($list);