简体   繁体   English

获取从现在到x天之间的所有日期

[英]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: 此函数将返回填充DateTime对象的数组,从今天到今天+ X天:

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 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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