简体   繁体   中英

Get all dates between now and x days from now

I am trying to call a function that will return all the days between now and a variable number of days into the past. Below is some pseudo code mixed with real code. Can you guys help out so that it'll return an array of all the days?

function getTimeStamps($numDays){
    $today = date("Y-m-d");
    $startDate = $today - $numdays;
    $movingDay = $startDate;

    $results = array();
    while($movingDay <= $today){
        array_push($results,$movingDay);
        $movingDay + 1 day;
    }
    return $results;
}
    $dateList = getTimeStamps(8);

This function would return

array(
    '2013-12-10',
    '2013-12-11',
    '2013-12-12',
    '2013-12-13',
    '2013-12-14',
    '2013-12-15',
    '2013-12-16',
    '2013-12-17'
);

This should do the heavy lifting of what you need. You can modify it to suit your exact purposes.

$start    = new DateTime('2013-12-01');
$end      = new DateTime('2013-12-17');
$interval = new DateInterval('P1D');
$period   = new DatePeriod($start, $interval, $end);

foreach ($period as $dt)
{
    echo $dt->format("Y-m-d") . PHP_EOL;
}

See it in action

function getTimeStamps($numDays){
     $dates = array();
     for ($i=$numDays-1; $i>=0; $i--){
         $dates[] = date("Y-m-d", strtotime("now - $i days"));
     }
     return $dates;
}

So...

print_r(getTimeStamps(8));

Prints out:

Array
(
    [0] => 2013-12-10
    [1] => 2013-12-11
    [2] => 2013-12-12
    [3] => 2013-12-13
    [4] => 2013-12-14
    [5] => 2013-12-15
    [6] => 2013-12-16
    [7] => 2013-12-17
)

Johhn's answer is great; to complement, this is an example using the more old fashioned timestamps, wrapped in a generator:

function getPastDates($daysAgo)
{
    $current = strtotime(sprintf('-%d days', $daysAgo));

    for ($i = 0; $i < $daysAgo; ++$i) {
        yield $current;
        $current = strtotime('+1 day', $current);
    }
}

foreach (getPastDates(7) as $ts) {
    echo date('Y-m-d', $ts), "\n";
}

This function will return you array filled with DateTime objects, from today to today+X days:

function getTimeStamps($numDays) {
    $now      = new DateTime('today');
    $interval = new DateInterval('P1D');
    $periods  = new DatePeriod($now, $interval, $numDays-1);
    return iterator_to_array($periods);
}

If you wish to format dates differently, just loop over them:

$datesBefore = getTimeStamps(4);
$datesAfter = array_map(function($dt) { return $dt->format('Y-m-d'); }, $datesBefore);

demo

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