Dukeatcoding
Dukeatcoding

Reputation: 1393

php DatePeriod does not return 2 days as expected

I try to get all days within a period of time. It does not matter if it is a full day or only some hours. My current code using DatePeriod does not work for me.

Example:

[start] => DateTime Object
    (
        [date] => 2014-01-27 22:40:40
        [timezone_type] => 1
        [timezone] => +00:00
    )

[end] => DateTime Object
    (
        [date] => 2014-01-28 17:40:40
        [timezone_type] => 1
        [timezone] => +00:00
    )

$interval = new DateInterval('P1D'); // 1Day Interval
$daterange = new DatePeriod($time['start'], $interval ,$time['end']);

$return['days'] = array();

foreach($daterange as $date){
    $return['days'][] = $date->format("Y-m-d");
}

I would like to get

[0] => 2014-01-27
[1] => 2014-01-28

But i only get the

[0] => 2014-01-27

Is it possible to change DatePeriod parameters or something ?

Upvotes: 2

Views: 4426

Answers (2)

Glavić
Glavić

Reputation: 43572

DatePeriod object ignores last period. You can solve that by increasing end date by your interval:

$interval = new DateInterval('P1D');
$start->setTime(0, 0);
$end->setTime(0, 0)->add($interval);
$periods = new DatePeriod($start, $interval, $end);

demo

Updated: remove (set to 00:00:00) time parts on start and end dates, if you are only looping via days.

Upvotes: 10

vascowhite
vascowhite

Reputation: 18430

You have fallen foul of the fact that DatePeriod ignores the last period. You can get around this by adding a DatePeriod to the end as Glavic suggests, or, you can construct DatePeriod using the number of intervals you want to add on, 1 in your given example:-

$interval = new DateInterval('P1D'); // 1Day Interval
$daterange = new DatePeriod($time['start'], $interval , 1);

$return['days'] = array();

foreach($daterange as $date){
    $return['days'][] = $date->format("Y-m-d");
}

See it working.

Glavic's answer is the best option here and you should accept that, I just wanted to show you an alternative as he got in too quick with the answer as usual :)

Upvotes: 3

Related Questions