How to fix correct the date in this case?

Viewed 46

Tell me please, we have a date, for example 2020-06-15. I need to add one month one year ahead, and also change the date to the last day of the month. That is, in the result it should turn out:

  • 2020-06-15 (first date)
  • 2020-07-31 (31 days in July)
  • 2020-08-31 (31 days in August)
  • 2020-09-30 (30 days in September)
  • 2020-10-31 (31 days in October)

and so on until July 22 year.

I try like this:

            foreach ($getDates as $getDate) {
            # Suppose getDate contains - 2020-06-15
            $firstDate = new \DateTime($getDate);
            $datesArr[] = $firstDate->format('Y-m-d');
                for ($i = 1; $i <= 12; $i++) {
                    $date = new \DateTime($getDate);

                    $month = $date->format('F');
                    $year = $date->format('Y');

                    $date->modify("+$i month");
                    # until this moment everything is fine, one by one months is added one year in advance
                    $date->modify("last day of $month $year");
                    # everything breaks here, although the documentation states "last day of July 2008"
                    $datesArr[] = $date->format('Y-m-d');
                }
        }

but it doesn't work quite correctly after the line modify("last day of $month $year"); tell me how to fix it?

2 Answers

You need to get the values in $month and $year after changing the date $date->modify("+$i month");, not before :

<?php
$getDate = '2020-06-15';
$firstDate = new \DateTime($getDate);
$datesArr[] = $firstDate->format('Y-m-d');
for ($i = 1; $i <= 12; $i++) {
    $date = new \DateTime($getDate);

    $date->modify("+$i month");
    
    // ----- Changes here -----
    $month = $date->format('F');
    $year = $date->format('Y');
    // ------------------------
    
    $date->modify("last day of $month $year");
    
    $datesArr[] = $date->format('Y-m-d');
}
var_dump($datesArr);

This outputs :

array(13) {
  [0]=>
  string(10) "2020-06-15"
  [1]=>
  string(10) "2020-07-31"
  [2]=>
  string(10) "2020-08-31"
  [3]=>
  string(10) "2020-09-30"
  [4]=>
  string(10) "2020-10-31"
  [5]=>
  string(10) "2020-11-30"
  [6]=>
  string(10) "2020-12-31"
  [7]=>
  string(10) "2021-01-31"
  [8]=>
  string(10) "2021-02-28"
  [9]=>
  string(10) "2021-03-31"
  [10]=>
  string(10) "2021-04-30"
  [11]=>
  string(10) "2021-05-31"
  [12]=>
  string(10) "2021-06-30"
}

It becomes a little shorter when the expression "last day of next month" is used.

$getDate = '2020-06-15';
$date = new \DateTime($getDate);
$datesArr[] = $date->format('Y-m-d');

for ($i = 1; $i <= 12; $i++) {
  $datesArr[] = $date
   ->modify("last day of next month")
   ->format('Y-m-d')
  ;
}

var_dump($datesArr);
Related