Search code examples
phpdatetimedecrement

How to decrement months on a php datetime object until it matches the month of a second date time object?


I have two objects $o_NewRegDate (registration date) and $o_NewNowDate(current date).

If we dump the year and month for $o_NewRegDate:

var_dump (date_format($o_NewRegDate, 'Y-m'));

string '2009-09' (length=7)

If we dump the year and month for $o_NewNowDate:

var_dump (date_format($o_NewNowDate, 'Y-m'));

    string '2013-09' (length=7)

What is the best way to decrement the months in $o_NewNowDate (storing each iteration in an array) until we reach the year and month of $o_NewRegDate?

Desired Output array would be something like this:

array (size=61)
  '2013-09-01' => string '09-2013' (length=7)
  '2013-08-01' => string '08-2013' (length=7)
  '2013-07-01' => string '07-2013' (length=7)
  (...)
  '2010-01-01' => string '01-2010' (length=7)
  '2009-12-01' => string '12-2009' (length=7)
  '2009-11-01' => string '11-2009' (length=7)
  '2009-10-01' => string '10-2009' (length=7)
  '2009-09-01' => string '09-2009' (length=7)

Solution

  • $o_NewRegDate = '2009-09-01';
    $o_NewNowDate = '2013-09-18';
    
    $startDate = new \DateTime($o_NewNowDate);
    echo 'Start date: ', $startDate->format('Y-m-d') , PHP_EOL;
    $endDate = new \DateTime($o_NewRegDate);
    echo 'End date: ', $endDate->format('Y-m-d') , PHP_EOL;
    
    $interval = new \DateInterval('P1M');
    $monthPeriod = new \DatePeriod ($endDate, $interval, $startDate);
    
    foreach ($monthPeriod as $key => $monthDate) {
       echo $monthDate->format('Y-m') , PHP_EOL;
    }