cabita
cabita

Reputation: 852

Get range of dates by month between range of dates

I have these dates:

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

I need get the follow ranges according to the month dynamically:

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

I need get ranges of dates dynamically by month from a start date and end date.

Can you help me? Thanks.

Upvotes: 1

Views: 1814

Answers (2)

user898741
user898741

Reputation:

<?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);

?>

Upvotes: 3

Nick Baluk
Nick Baluk

Reputation: 2275

<?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') );
?>

Upvotes: 2

Related Questions