Aniket Singh
Aniket Singh

Reputation: 877

How to get Months between two dates

I'm trying to get All the months between two dates.

for e.g if the user posted an article on 21-10-2012 and today date is 5-12-2017. Now i want to get all the month and Year between this period like shown below

10-2012
11-2012
01-2013
02-2014
03-2015
04-2015
05-2015
06-2015
07-2015 // and so on
.......
.......
.......
12-2017 // Till Today Date

Till Now i was only able to calculate the difference.

$article_date= date("d-m-Y", $article['date']);
$year = date("Y");
$month = date("m");
$day = date("d");
$date1 = new DateTime($article_date);
$date2 = new DateTime("$day-$month-$year");

$diff = $date1->diff($date2);

echo (($diff->format('%y') * 12) + $diff->format('%m')) . " full months difference";

How can i get all the months?

Upvotes: 1

Views: 2055

Answers (2)

Javid Karimov
Javid Karimov

Reputation: 465

function list_months($date_from,$date_to, $return_format){
        $arr_months = array();
        $a =  new \DateTime($date_from);
        $x =  new \DateTime($date_to);

        $start = $a->modify('first day of this month');
        $end = $x->modify('first day of next month');

        $interval = \DateInterval::createFromDateString('1 month');
        $period = new \DatePeriod($start, $interval, $end);

        foreach ($period as $dt) {
            $arr_months[] = $dt->format($return_format);
        }

        return $arr_months ;
    }

Example: $new_list = list_months('11-10-2012','11-10-2017', 'm-Y');

Upvotes: 1

Ravinder Reddy
Ravinder Reddy

Reputation: 3879

Use this code

$start    = new DateTime('2012-10-21');
$start->modify('first day of this month');
$end      = new DateTime('2017-12-05');
$end->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period   = new DatePeriod($start, $interval, $end);

foreach ($period as $dt) {
    echo $dt->format("m-Y") . "<br>\n";
}

Upvotes: 2

Related Questions