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

use*_*734 53 php php-carbon

如何在PHP中获取两个日期之间的所有日期?喜欢使用碳作日期.

$from = Carbon::now();
$to = Carbon::createFromDate(2017, 5, 21);
Run Code Online (Sandbox Code Playgroud)

我想在这两个日期之间有所有日期..但是怎么样?只能找到使用strtotime功能的解决方案.

Pau*_*aul 65

从碳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();
Run Code Online (Sandbox Code Playgroud)

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

  • 请记住,您还可以使用 `$date->toDateString()` 来获取格式为 `Ymd` 的日期。[文档](https://carbon.nesbot.com/docs/#api-formatting)。 (3认同)

Seb*_*ski 60

这是我如何做到的 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 难道你不会有`$ start_date`最终等于`$ end_date`的问题?如果你想在调用这个函数后继续使用原始的`$ start_date`,你应该将原始的`$ start_date`的副本传递给这个函数,或者在你的函数中设置`$ date = $ start_date - > copy()` `for`-loop的定义,我更喜欢. (2认同)

Mar*_*ker 17

由于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;
}
Run Code Online (Sandbox Code Playgroud)

编辑

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

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

foreach($daterange as $date){
    echo $date->format("Ymd"), PHP_EOL;
}
Run Code Online (Sandbox Code Playgroud)


Tri*_*ier 9

基于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;
}
Run Code Online (Sandbox Code Playgroud)

用法:

>>> 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",
     },
   ]
Run Code Online (Sandbox Code Playgroud)

您还可以传递boolean(false)作为第三个参数来排除结束日期.


Dar*_*s.V 5

这是我所拥有的:

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;
    }
Run Code Online (Sandbox Code Playgroud)

例子:

$this->getDatesFromRange('2015-03-15 10:10:10', '2015-03-19 09:10:10');
Run Code Online (Sandbox Code Playgroud)


Jon*_*han 5

这也可以这样做:

new DatePeriod($startDate, new DateInterval('P1D'), $endDate)
Run Code Online (Sandbox Code Playgroud)

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

iterator_to_array(new DatePeriod($startDate, new DateInterval('P1D'), $endDate))
Run Code Online (Sandbox Code Playgroud)

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

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

现在你可以这样做:

foreach (Carbon::range($start, $end) as $date) {
   // ...
}
Run Code Online (Sandbox Code Playgroud)