Nandu
Nandu

Reputation: 3126

Last day of each month within a date range in php

How to get last day of each month within a date range in PHP?

Input:

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

The output that I want is:

2013-01-31 End date of January
2013-02-28 End date of February
2013-03-15 *End date of March is '2013-03-31' but the end date is '2013-03-15' .

So I want 2013-03-15.

How can I do that?

Upvotes: 0

Views: 1660

Answers (3)

Michael Makarenkov
Michael Makarenkov

Reputation: 1

I'm little changed the function:

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;
}

Upvotes: 0

Bhavik Shah
Bhavik Shah

Reputation: 2291

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 will have the output you want. It will work even if years are different. Logic is from this URL

Upvotes: 2

Pankrates
Pankrates

Reputation: 3094

In the future, try to write the code yourself. If you are stuck with a specific part you can request help. Exception for this one time:

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

Will output:

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

Note that this does not work if the start and end dates have a different year. I have left this as an exercise.

Upvotes: 4

Related Questions