获得两个给定日期之间的年和月列表的精巧方法

时间:2012-08-14 01:44:50

标签: php date

我希望得到两个给定日期之间的年份和月份列表

这是我的代码

    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秒,但闰年并不是很准确

有没有更干净的方法呢?

1 个答案:

答案 0 :(得分:2)

我有两个解决方案,要么改变现有代码,要么使用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);