在日期范围之间按月获取日期范围

时间:2011-11-30 11:19:38

标签: php

我有这些日期:

start date:  5/08/2011
end date:  16/11/2011

我需要根据月份动态获得以下范围:

5/08/2011-31/08/2011
1/09/2011-30/09/2011
1/10/2011-31/10/2011
1/11/2011-16/11/2011

我需要从开始日期和结束日期开始按月动态获取日期范围。

你能帮帮我吗?感谢。

2 个答案:

答案 0 :(得分:3)

<?php

$start_date = list($sDay, $sMonth, $sYear) = explode("/", "05/08/2011");
$end_date   = list($eDay, $eMonth, $eYear) = explode("/", "16/11/2011");

$startMonth = $sMonth;
do
{
    $mk = mktime(0, 0, 0, $sMonth, 1, $sYear);
    $mY = date("mY", $mk);
    $endFormat = "t/m/Y";

    if ($sMonth == $startMonth)
    {
        $mk = mktime(0, 0, 0, $sMonth, $sDay, $sYear);
    }
    else if ($mY == $eMonth . $eYear)
    {
        $endFormat = $eDay . "/m/Y";
    }

    echo date("d/m/Y", $mk)    . " - " . 
         date($endFormat, $mk) . "<br />";

    $sMonth++;
}
while ($eMonth . $eYear > $mY);

?>

答案 1 :(得分:2)

<?php


function dateRange( $first, $last, $step = '+1 month', $format = 'd/m/Y' ) {

    $dates = array();
    $current = strtotime( $first );
    $last = strtotime( $last );

    while( $current <= $last ) {

        $dates[] = date( $format, $current );
        $current = strtotime( $step, $current );
    }

    return $dates;
}
print_r( dateRange( '2010/01/26', '2010/08/05') );
?>