简体   繁体   中英

Is there any more simple way to get all months and years list between two dates then mine

I want to get all months and year in turn in an array between two dates. I want the output like this format: Ym

I done it. But, I just want to know is there any simple way to get the same result.

There is my code:

public function __construct()
{
    $this->params['start-date'] = date('Y-m-d', strtotime("01-01-2016"));
    $this->params['end-date'] = date('Y-m-d', time());
}

/**
 * @return array
 */
private function _getAllMonths()
{
    $start  = date_parse($this->params["start-date"]);
    $end  = date_parse($this->params["end-date"]);

    $output[] = ['month' => $start["year"]."-0".$start["month"]];
    //loop years
    for($i=(int)$start["year"];$i<=(int)$end["year"];$i++)
    {
        //control months and start year
        $k = $i == $start["year"] ? (int)$start["month"] + 1 : 1;
        //loop months
        for($j=$k;$j<13;$j++)
        {
            if($i==$end["year"] && $j==$end["month"])
                break;
            $output[] = ["month" => $i."-".str_pad($j, 2, "0", STR_PAD_LEFT)];
        }
    }
    return $output;
}

Please explain me how?

How about this to get you started

$start = new \DateTime('now');
$end = new \DateTime('now + 3 years');
$interval = new \DateInterval('P1M');
$period = new \DatePeriod($start, $interval, $end);

foreach($period as $date) {
    echo $date->format('Y-m-d H:i:s') . "\n";
}

Not a huge step to adapt it to your needs

PHP Manual Pages

  1. DateTime
  2. DateInterval
  3. DatePeriod

If you're doing a lot with dates I recommend a library called Carbon

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM