new_newB1e
new_newB1e

Reputation: 155

PHP script date modify issue when using in loop

EDITED directly to the problem :

The code :

<?php

$date = new DateTime('2000-01-31'); // or whatever

for ($i = 0; $i < 100; $i++) {
    $currentDay = $date->format('d');

    if ($currentDay < $date->format('t')) {

        $date->modify('+1 month');

        if ($date->format('d') < $currentDay) {
            $date->modify('last day of previous month');
        }
    } else {
        $date->modify('last day of next month');
    }

    echo $date->format('Y-m-d') . "<br>";
}

So, if starting date is 2000-01-31, it works fine. That's just because 31 is the last day of january, so, any other month it will put the last date of the month.

But, if u change starting date to 2000-01-30, it's broken. That's because 30 january is not the last day in january. But anyway, 30 january is greater than days in february, so it transform date to 28/29 february. Since 28/29 february is the last day in february, it proceed the code like when this date == number of days in the month, and on the next iteration instead of putting 30 march, it puts 'last day of next month' (31 of march). And that's not the unique case. Same thing if u put starting date for example 30-08-2000. 30 is not the last day of august, so it change the date to 30 of september, 30 september is the last day of the september, so it change the date to 31 of octomber, but it's not what I expect.

Upvotes: 1

Views: 434

Answers (2)

Rwd
Rwd

Reputation: 35190

If I've understood your question correctly then this should be what you're after:

$date = new DateTime('2000-01-31'); // or whatever
$day = $date->format('d');
$date->setDate($date->format('Y'), $date->format('m'), 1);

for ($i = 0; $i < 100; $i++) {

    $date->modify('+1 month');

    echo echo $date->format('t') < $day ? $date->format('Y-m-t') : $date->format('Y-m-' . $day);
    echo '<br />';
}

Hope this helps!

Upvotes: 2

dweller
dweller

Reputation: 36

Do I understand correctly that

  • you want to print the same day for all following months
  • in case it's higher than the maximum days in the month, last day of that month should be used instead

If yes, this could work:

<?php
$date = new DateTime('2000-01-28'); // or whatever
#echo $date->format('d')." ".$date->format('t');
$expectedDay = $date->format('d');
$month = $date->format('m');
$year = $date->format('Y');

for ($i = 0; $i < 100; $i++) {
    echo $date->format('Y-m-d')  . "<br>"; 
    if ($month++ == 12) {
        $year++;
        $month = 1;
    }

    $date->modify("${year}-${month}-1");
    if ($expectedDay > $date->format('t')) {
        $day = $date->format('t');
    } else {
        $day = $expectedDay;    
    }
    $date->modify("${year}-${month}-${day}");
}    

Upvotes: 0

Related Questions