0

When executing the following code, PHP only shows month 10 and 12, ignoring month 11 at all.

    $sollStart = '2019-10-31 00:00:01';
    $sollEnde = '2019-12-31 23:59:59';
    $start = new DateTime($sollStart);
    $end = new DateTime($sollEnde);
    $periodInterval = new \DateInterval('P1M');
    $periodIterator = new \DatePeriod($start, $periodInterval, $end);
    foreach ($periodIterator as $monat) {
        echo $monat->format('m');           
    }

If I change the start date to 2019-10-30 it is working like expected.

I've no idea what to change to make it work.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • I suppose that __month__ is considered as __31__ days. That's why adding 31 days to October, 31 will give you December, 1. – u_mulder Dec 13 '19 at 20:56
  • If you show full dates not just months you get "2019-10-31" and "2019-12-01". – gre_gor Dec 13 '19 at 20:57
  • You could alternatively start with `2019-11-01 00:00:01` and then take 1 day off in the loop `echo $monat->modify("-1 day")->format('m');`. – Nigel Ren Dec 13 '19 at 21:06

1 Answers1

-1

Try this:

$sollstart    = (new DateTime('2019-10-31 00:00:01'))->modify('first day of this month');
$sollend      = (new DateTime('2019-12-31 23:59:59'))->modify('first day of this month');
$interval = DateInterval::createFromDateString('1 month');
$period   = new DatePeriod($sollstart, $interval, $sollend);

foreach ($period as $m) {
    echo $m->format("m") . "<br>";
}
BCM
  • 665
  • 5
  • 20
  • This solved my problem. I've done some other testing and it looks like the last day is not included in period? – Ralf Puppe Dec 14 '19 at 03:33
  • @Ralf Puppe $sollend = (new DateTime('2019-12-31 23:59:59'))->modify('last day of this month'); Use last day of this month on your sollend – BCM Dec 14 '19 at 10:51