1

I am trying to get an array of datetime objects but failing miserably.

I want to take today's date, and get all dates within the last 30 days.

$today = new DateTime();
$begin = $today->sub(new DateInterval('P30D'));

$interval = new DateInterval('P1D'); // 1 Day
$dateRange = new DatePeriod($begin, $interval, $today);

$range = [];
foreach ($dateRange as $date) {
    $range[] = $date->format('Y-m-d');
}

When I dump out $range, I get an empty array.

What am I doing wrong?

Peter Griffin
  • 300
  • 5
  • 18

3 Answers3

3

Change

$begin = $today->sub(new DateInterval('P30D'));

to

$begin = new DateTime();
$begin->sub(new DateInterval('P30D'));
AdRock
  • 2,959
  • 10
  • 66
  • 106
1

you overwrite $today so $today and $begin is exactly the same

$today =  new DateTime();
$copy = clone $today;
$begin = $copy->sub(new DateInterval('P30D'));

$interval = new DateInterval('P1D'); // 1 Day
$dateRange = new DatePeriod($begin, $interval, $today);

$range = [];
foreach ($dateRange as $date) {
    $range[] = $date->format('Y-m-d');
}

will work

Frankich
  • 842
  • 9
  • 19
1

the "sub" method modifies the source object, as well as outputting the object itself as the return value (really this is intended for method chaining). It doesn't just create a new object with the new date.

$begin = $today->sub(new DateInterval('P30D'));

modifies $today as well as outputting a copy which you then declare as $begin. This results in both objects having the same date, and thus there's no time interval over which to iterate.

See http://php.net/manual/en/datetime.sub.php

You need to create a separate object for your end date:

$begin = new DateTime();
$begin->sub(new DateInterval('P30D'));
$end = new DateTime();

$interval = new DateInterval('P1D'); // 1 Day
$dateRange = new DatePeriod($begin, $interval, $end);

$range = [];
foreach ($dateRange as $date) {
    $range[] = $date->format('Y-m-d');
}
var_dump($range);

See it working at https://eval.in/867948

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • Please transfer this good answer to this much earlier duplicate that is loaded with not-so-good answers. https://stackoverflow.com/q/337760/2943403 – mickmackusa Apr 30 '18 at 04:01