如何在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。
我怎样才能做到这一点?
如何在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。
我怎样才能做到这一点?
以后尽量自己写代码。如果您遇到特定部分,您可以请求帮助。这一次例外:
<?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
请注意,如果开始日期和结束日期的年份不同,这将不起作用。我把这个作为练习。
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
我几乎没有改变功能:
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;
}