Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list all months between two dates

Tags:

date

php

datetime

I'm trying to list all months between two dates.

For example; start date is: 2010-12-02 and last date is: 2012-05-06

I want to list something like this:

2010-12 2011-01 2011-02 2011-03 2011-04 . . . 2012-04 2012-05 

This is what I have tried and it is not working at all:

    $year_min = 2010;     $year_max = 2012;     $month_min = 12;     $month_max = 5;     for($y=$year_min; $y<=$year_max; $y++)     {         for($m=$month_min; $m<=$month_max; $m++)         {             $period[] = $y.$m;         }     } 
like image 311
Pooya Avatar asked Sep 11 '13 13:09

Pooya


People also ask

How do I calculate months between two dates in Excel?

To find the number of months or days between two dates, type into a new cell: =DATEDIF(A1,B1,”M”) for months or =DATEDIF(A1,B1,”D”) for days.


1 Answers

PHP 5.3

$start    = new DateTime('2010-12-02'); $start->modify('first day of this month'); $end      = new DateTime('2012-05-06'); $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("Y-m") . "<br>\n"; } 

See it in action

PHP 5.4 or newer

$start    = (new DateTime('2010-12-02'))->modify('first day of this month'); $end      = (new DateTime('2012-05-06'))->modify('first day of next month'); $interval = DateInterval::createFromDateString('1 month'); $period   = new DatePeriod($start, $interval, $end);  foreach ($period as $dt) {     echo $dt->format("Y-m") . "<br>\n"; } 

The part where we modify the start and end dates to the first of the month is important. If we didn't, and the current day higher then the last day in February (i.e. 28 in non-leap years, 29 in leap years) this would skip February.

like image 167
John Conde Avatar answered Oct 10 '22 19:10

John Conde