user9632001
user9632001

Reputation:

Get the last 12 months in PHP from Month Year Given

Problem: I need to find year-month strings between two given dates in the format "Y-m".

I have this, but it does not work:

for ($i = 0; $i <= 12; $i++) {
    $months[] = date("Y-m%", strtotime(date('Y-m-01') . " -$i months"));
}

Because this starts today, and only for 12 month.

Example given date:

11-2015 to 05-2018

Upvotes: 0

Views: 639

Answers (2)

spinkus
spinkus

Reputation: 8550

You can use DatePeriod to get a range of dates between 2 DateTimes, then use DateTime::format() to get what ever date string you want from those dates (in your case 'Y-m'):

<?php
$dates = new DatePeriod(new DateTime('2015-01'), new DateInterval('P1M'), new DateTime('2018-05'));
$date_strings = array_map(function($d) { return $d->format('Y-m'); }, iterator_to_array($dates));
print_r($date_strings);

Gives:

Array
(
    [0] => 2015-01
    [1] => 2015-02
    [2] => 2015-03
    [3] => 2015-04
    [4] => 2015-05
    [5] => 2015-06
    ...
    [39] => 2018-04
)

Upvotes: 2

user9632001
user9632001

Reputation:

correct way:

                $date1=$s_list_102."-".$s_list_101."-01"; //month and year merge on date 1
                $date2=$s_list_104."-".$s_list_103."-01"; //month and year merge on date 1
                $d1 = strtotime($date1);
                $d2 = strtotime($date2);
                $min_date = min($d1, $d2);
                $max_date = max($d1, $d2);
                $c = 0;
                while (($min_date = strtotime("+1 MONTH", $min_date)) <= $max_date) {
                    $c++;
                }
                for ($i = 0; $i <= $c; $i++) {
                    $months[] = date("M-y", strtotime(date($date2) . " -$i months"));
                }

Upvotes: 1

Related Questions