Ajeesh Joshy
Ajeesh Joshy

Reputation: 1537

Weird PHP issue - DatePeriod does not show February while iterating through months.

This is my code

$from = '2014-10-01 00:00:00';
$to = '2015-05-31 23:30:00';

$start = new DateTime('@' . strtotime($from), new DateTimeZone('Asia/Dubai'));
$end = new DateTime('@' . strtotime($to), new DateTimeZone('Asia/Dubai'));
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);

$count = 0;

foreach ($period as $dt) {
    echo $dt->format('Y-M').'<br>';
}

exit;

I need to get the month's starting date and month's ending date for a certain period. So, I use the DatePeriod.

But, this only shows this output.

2014-Sep
2014-Oct
2014-Nov
2014-Dec
2015-Jan
2015-Mar
2015-Apr
2015-May

And somehow the month February is missed.

Can anyone help me on this ?

Upvotes: 1

Views: 435

Answers (1)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21422

Just remove strtotime and @ from the code and it'll work fine. As there is no need to make a timestamp of your date value

$from = '2014-10-01 00:00:00';
$to = '2015-05-31 23:30:00';

$start = new DateTime($from, new DateTimeZone('Asia/Dubai'));
$end = new DateTime($to, new DateTimeZone('Asia/Dubai'));
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);

$count = 0;

foreach ($period as $dt) {
    echo $dt->format('Y-M').'<br>';
}

Upvotes: 1

Related Questions