2

Using code from this post https://stackoverflow.com/a/4312630/257629

I am getting an empty object when attempting to use DatePeriod(). My PHP is version 5.4.3 and I can't see any errors. The DateTime and DateInterval appear to return the correct objects, but when passing it to the DatePeriod, I am left with an empty object. (debug is from CakePHP and outputs the contents of the variable.)

// values passed from form, to a function
// $arrival = 2013-09-05
// $departure = 2013-08-16

$start = new DateTime($arrival);
/*
object(DateTime) {
date => '2013-09-05 00:00:00'
timezone_type => (int) 3
timezone => 'UTC'
}
*/

$interval = new DateInterval('P1D');
/*
object(DateInterval) {
    y => (int) 0
    m => (int) 0
    d => (int) 1
    h => (int) 0
    i => (int) 0
    s => (int) 0
    invert => (int) 0
    days => false
}
*/

$end = new DateTime($departure);
/*
object(DateTime) {
date => '2013-08-16 00:00:00'
timezone_type => (int) 3
timezone => 'UTC'
}
*/

$period = new DatePeriod($start, $interval, $end);

debug($period);
/*
object(DatePeriod) {

}
*/

foreach ($period as $date) {
    echo $date->format('Y-m-d')."\n";
}
Community
  • 1
  • 1

2 Answers2

1
$arrival = 2013-09-05
$departure = 2013-08-16

Arrival is not greater than Departure. If you set $arrival = 2013-08-05. Then output will be

2013-08-05
2013-08-06
2013-08-07
2013-08-08
2013-08-09
2013-08-10
2013-08-11
2013-08-12
2013-08-13
2013-08-14
2013-08-15
som
  • 4,650
  • 2
  • 21
  • 36
1

$end date is before $start date because you mixed up $arrival and $departure vars

NDM
  • 6,731
  • 3
  • 39
  • 52