简体   繁体   中英

Get all dates from last 30 days (datetime objects)

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?

Change

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

to

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM