PHP Carbon,获取日期范围内的所有日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31849334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:39:51  来源:igfitidea点击:

PHP Carbon, get all dates between date range?

phpphp-carbon

提问by user1469734

How can I get all dates between two dates in PHP? Prefer using Carbon for dates.

如何在PHP中获取两个日期之间的所有日期?喜欢用 Carbon 做日期。

$from = Carbon::now();
$to = Carbon::createFromDate(2017, 5, 21);

I wanna have all dates between those two dates.. But how? Can only found solutions using strtotime function.

我想要这两个日期之间的所有日期..但是如何?只能使用 strtotime 函数找到解决方案。

回答by Paul

As of Carbon 1.29 it is possible to do:

从 Carbon 1.29 开始,可以执行以下操作:

$period = CarbonPeriod::create('2018-06-14', '2018-06-20');

// Iterate over the period
foreach ($period as $date) {
    echo $date->format('Y-m-d');
}

// Convert the period to an array of dates
$dates = $period->toArray();

See documentation for more details: https://carbon.nesbot.com/docs/#api-period.

有关更多详细信息,请参阅文档:https: //carbon.nesbot.com/docs/#api-period

回答by Sebastian Sulinski

Here's how I did it with Carbon

这是我如何做到的 Carbon

private function generateDateRange(Carbon $start_date, Carbon $end_date)
{
    $dates = [];

    for($date = $start_date->copy(); $date->lte($end_date); $date->addDay()) {
        $dates[] = $date->format('Y-m-d');
    }

    return $dates;
}

回答by Mark Baker

As Carbon is an extension of PHP's built-in DateTime, you should be able to use DatePeriod and DateInterval, exactly as you would with a DateTime object

由于 Carbon 是 PHP 内置 DateTime 的扩展,您应该能够使用 DatePeriod 和 DateInterval,就像使用 DateTime 对象一样

$interval = new DateInterval('P1D');
$to->add($interval);
$daterange = new DatePeriod($from, $interval ,$to);

foreach($daterange as $date){
    echo $date->format("Ymd"), PHP_EOL;
}

EDIT

编辑

If you need to include the final date of the period, then you need to modify it slightly, and adjust $tobefore generating the DatePeriod

如果需要包含期间的最后日期,则需要稍作修改,并$to在生成DatePeriod之前进行调整

$interval = new DateInterval('P1D');
$daterange = new DatePeriod($from, $interval ,$to);

foreach($daterange as $date){
    echo $date->format("Ymd"), PHP_EOL;
}

回答by Tristan Jahier

Based on Mark Baker's answer, I wrote this function:

根据 Mark Ba​​ker 的回答,我写了这个函数:

/**
 * Compute a range between two dates, and generate
 * a plain array of Carbon objects of each day in it.
 *
 * @param  \Carbon\Carbon  $from
 * @param  \Carbon\Carbon  $to
 * @param  bool  $inclusive
 * @return array|null
 *
 * @author Tristan Jahier
 */
function date_range(Carbon\Carbon $from, Carbon\Carbon $to, $inclusive = true)
{
    if ($from->gt($to)) {
        return null;
    }

    // Clone the date objects to avoid issues, then reset their time
    $from = $from->copy()->startOfDay();
    $to = $to->copy()->startOfDay();

    // Include the end date in the range
    if ($inclusive) {
        $to->addDay();
    }

    $step = Carbon\CarbonInterval::day();
    $period = new DatePeriod($from, $step, $to);

    // Convert the DatePeriod into a plain array of Carbon objects
    $range = [];

    foreach ($period as $day) {
        $range[] = new Carbon\Carbon($day);
    }

    return ! empty($range) ? $range : null;
}

Usage:

用法:

>>> date_range(Carbon::parse('2016-07-21'), Carbon::parse('2016-07-23'));
=> [
     Carbon\Carbon {#760
       +"date": "2016-07-21 00:00:00.000000",
       +"timezone_type": 3,
       +"timezone": "UTC",
     },
     Carbon\Carbon {#759
       +"date": "2016-07-22 00:00:00.000000",
       +"timezone_type": 3,
       +"timezone": "UTC",
     },
     Carbon\Carbon {#761
       +"date": "2016-07-23 00:00:00.000000",
       +"timezone_type": 3,
       +"timezone": "UTC",
     },
   ]

You can also pass a boolean (false) as third argument to exclude the end date.

您还可以将布尔值 ( false) 作为第三个参数传递以排除结束日期。

回答by Jonathan

This can also be done like this:

这也可以这样做:

new DatePeriod($startDate, new DateInterval('P1D'), $endDate)

Just keep in mind that DatePeriodis an iterator, so if you want an actual array:

请记住这DatePeriod是一个迭代器,所以如果你想要一个实际的数组:

iterator_to_array(new DatePeriod($startDate, new DateInterval('P1D'), $endDate))

In you're using Laravel, you could always create a Carbon macro:

在你使用 Laravel 时,你总是可以创建一个 Carbon 宏:

Carbon::macro('range', function ($start, $end) {
    return new Collection(new DatePeriod($start, new DateInterval('P1D'), $end));
});

Now you can do this:

现在你可以这样做:

foreach (Carbon::range($start, $end) as $date) {
   // ...
}

回答by latecoder

You can directly using Carbon

您可以直接使用碳

    $start = Carbon::createFromDate(2017, 5, 21);
    $end = Carbon::now();

    while($start < $end){
        echo $start->format("M");
        $start->addMonth();
    }

回答by Darius.V

Here is what I have:

这是我所拥有的:

private function getDatesFromRange($date_time_from, $date_time_to)
    {

        // cut hours, because not getting last day when hours of time to is less than hours of time_from
        // see while loop
        $start = Carbon::createFromFormat('Y-m-d', substr($date_time_from, 0, 10));
        $end = Carbon::createFromFormat('Y-m-d', substr($date_time_to, 0, 10));

        $dates = [];

        while ($start->lte($end)) {

            $dates[] = $start->copy()->format('Y-m-d');

            $start->addDay();
        }

        return $dates;
    }

Example:

例子:

$this->getDatesFromRange('2015-03-15 10:10:10', '2015-03-19 09:10:10');

回答by marcelo gutierrez

You can't use loop control variable directly, the next must be work fine

你不能直接使用循环控制变量,接下来必须工作正常

$start = Carbon::today()->startOfWeek();
$end = Carbon::today()->endOfWeek();

$stack = [];

$date = $start;
while ($date <= $end) {

    if (! $date->isWeekend()) {
        $stack[] = $date->copy();
    }
    $date->addDays(1);
}

return $stack;

回答by fico7489

Very simple solution (it works with old "<1.29" carbon ) :

非常简单的解决方案(它适用于旧的 "<1.29" carbon ):

// set $start and $end to any date
$start = Carbon::now()->addDays(-10);
$end = Carbon::now();

$dates = [];
for($i = 0; $i < $end->diffInDays($start); $i++){
    $dates[] = (clone $start)->addDays($i)->format('Y-m-d');
}
dd($dates);

回答by Jawad Multani

//To get just an array of dates, follow this.


        $period = CarbonPeriod::create('2018-06-14', '2018-06-20');

        $p = array();
    // If you want just dates
    // Iterate over the period and create push to array
        foreach ($period as $date) {
            $p[] = $date->format('Y-m-d');
        }

    // Return an array of dates

        return $p;