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

时间:2015-08-06 07:24:48

标签: php php-carbon

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

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

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

10 个答案:

答案 0 :(得分:59)

以下是我使用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;
}

答案 1 :(得分:42)

从碳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();

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

答案 2 :(得分: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;
}

修改

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

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

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

答案 3 :(得分: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;
}

用法:

>>> 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",
     },
   ]

你也可以传递一个布尔值(false)作为第三个参数来排除结束日期。

答案 4 :(得分:2)

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

$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;

答案 5 :(得分:2)

这也可以这样做:

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

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

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

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

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

现在你可以这样做:

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

答案 6 :(得分:2)

您可以直接使用Carbon

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

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

答案 7 :(得分:-1)

//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;

答案 8 :(得分:-1)

非常简单的解决方案(它适用于旧的“ <1.29”碳):

// 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);

答案 9 :(得分:-1)

本教程将提供 laravel carbon 获取两个日期之间所有月份的示例。一步一步解释laravel carbon get all月。这篇文章将为您提供碳获取日期之间所有月份的简单示例。我们将使用获取两个日期之间的所有月份 laravel carbon。在这里,创建一个获取两个日期之间的月份的基本示例 laravel。

  
namespace App\Http\Controllers;
  
use Carbon\Carbon;
use Carbon\CarbonPeriod;
  
class SignaturePadController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $result = CarbonPeriod::create('2020-01-01', '2020-12-01');
  
        foreach ($result as $dt) {
            echo $dt->format("Y-m");
        }
       $dates = $result->toArray();
    }
}

来源:https://www.itsolutionstuff.com/post/laravel-carbon-get-all-months-between-two-dates-exampleexample.html