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


72

如何在PHP中获取两个日期之间的所有日期?首选使用Carbon作为日期。

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

我想要两个日期之间的所有日期。只能使用strtotime函数找到解决方案。

Answers:


127

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

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


66

这是我的做法 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;
}

2
你不会有最后$start_date被平等的问题$end_date吗?如果要$start_date在调用此函数后继续使用原始文件,则应将原始文件的副本传递$start_date给此函数,或者$date = $start_date -> copy()for-loop的定义中进行设置,这是我希望的。
molerat

19

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

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

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

编辑

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

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

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

如果$ to time不大,则不会打印间隔中的最后日期。我的意思是至少秒必须更大一些,也许是毫秒级,没有尝试过
Dariux

添加了相关代码行以包括该时期的$ to日期
Mark Ba​​ker

11

基于马克·贝克的回答,我编写了以下函数:

/**
 * 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)作为第三个参数以排除结束日期。


5

也可以这样完成:

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) {
   // ...
}

3

这是我所拥有的:

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

例:

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

3

您可以直接使用Carbon

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

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

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;

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

令人惊讶的缓慢解决方案
user1469734'5

CarbonPeriod显然是最快的解决方案,但是它是Caarbon的相对新功能,许多应用程序无法使用它,我的解决方案涵盖了较早的Carbon版本,并且与@Sebastien的解决方案一样快...我刚刚对其进行了测量...。 ..
fico7489'5

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

请在您的答案中添加描述,以便任何人都可以理解您的代码算法。不要喂汤。
fendiSetiawan
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.