每个月的最后一天在php的日期范围内

时间:2013-02-01 10:29:33

标签: php

如何在PHP的日期范围内获取每个月的最后一天?

输入:

  

$ startdate ='2013-01-15'
  $ enddate ='2013-03-15'

我想要的输出是:

  

2013-01-31 1月结束日期
   2013-02-28 2月结束日期
   2013-03-15 * 3月结束日期为'2013-03-31',但结束日期为'2013-03-15'。

所以我想要2013-03-15

我该怎么做?

3 个答案:

答案 0 :(得分:4)

将来,请尝试自己编写代码。如果您遇到特定部分,可以请求帮助。这一次的例外情况:

<?php

$startdate  = new DateTime('2013-01-15'); 
$enddate    = new DateTime('2013-04-15');

$year = $startdate->format('Y');

$start_month    = (int)$startdate->format('m');
$end_month      = (int)$enddate->format('m');

for ( $i=$start_month; $i<$end_month; $i++) {
    $date = new DateTime($year.'-'.$i);
    echo $date->format('Y-m-t').' End date of '.$date->format('F');
}

echo $enddate->format('Y-m-d');

将输出:

2013-01-31 End date of January
2013-02-28 End date of February
2013-03-31 End date of March
2013-04-15

请注意,如果开始日期和结束日期的年份不同,则此方法无效。我把它留作练习。

答案 1 :(得分:1)

function get_months($date1, $date2) {

    $time1 = strtotime($date1);
    $time2 = strtotime($date2);

    $my = date('mY', $time2);
    $months = array(date('Y-m-t', $time1));
    $f = '';

    while($time1 < $time2) {
        $time1 = strtotime((date('Y-m-d', $time1).' +15days'));

        if(date('F', $time1) != $f) {
            $f = date('F', $time1);

            if(date('mY', $time1) != $my && ($time1 < $time2))
                $months[] = date('Y-m-t', $time1);
        }

    }

    $months[] = date('Y-m-d', $time2);
    return $months;
}

$myDates = get_months('2005-01-20', '2005-11-25');

$ myDates将拥有您想要的输出。即使年份不同,它也会奏效。逻辑来自URL

答案 2 :(得分:0)

我几乎没有改变这个功能:

function get_months($date1, $date2) {

    $time1 = strtotime($date1);
    $time2 = strtotime($date2);

    $my = date('mY', $time2);

    $f = '';

    while($time1 < $time2) {
        $time1 = strtotime((date('Y-m-d', $time1).' +15days'));

        if(date('F', $time1) != $f) {
            $f = date('F', $time1);

            if(date('mY', $time1) != $my && ($time1 < $time2))
                $months[] = array(date('Y-m-01', $time1),date('Y-m-t', $time1));
        }

    }

    $months[] = array(date('Y-m-01', $time2),date('Y-m-d', $time2));
    return $months;
}