Pick up and list months between dates of different years

Asked

Viewed 731 times

2

I have the following question. Starting date: 01/10/2017 and end date 01/10/2018. How can I list the months between these dates?

For example: October(17), November(17), December(17), January(18)...and so on until September(18(18)).

  • you want the full name?

1 answer

3


Following example:

// Data de ínicio
$start    = (new DateTime('2017-10-01'))->modify('first day of this month');
// Data final
$end      = (new DateTime('2018-10-01'))->modify('first day of next month');
// Define qual será o intervalo a ser calculado
$interval = DateInterval::createFromDateString('1 month');
// Cria o período de data entre o inicio, final e o intervalo
$period   = new DatePeriod($start, $interval, $end);

// conforme o intervalo, retorna todas datas
foreach ($period as $dt) {
   echo $dt->format("Y-m") . "<br>\n";
}

Online test: http://sandbox.onlinephpfunctions.com/code/3856a4b6b1e5450bdc65acad755150f248315903

  • Very good! That’s what I needed, will help a lot <3

Browser other questions tagged

You are not signed in. Login or sign up in order to post.