programing

PHP Carbon, 날짜 범위 사이의 모든 날짜를 얻습니까?

copysource 2021. 1. 16. 20:40
반응형

PHP Carbon, 날짜 범위 사이의 모든 날짜를 얻습니까?


PHP에서 두 날짜 사이의 모든 날짜를 어떻게 얻을 수 있습니까? 날짜에는 Carbon을 사용하는 것이 좋습니다.

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

두 날짜 사이에 모든 날짜를 갖고 싶어 ..하지만 어떻게? strtotime 함수를 사용하는 솔루션 만 찾을 수 있습니다.


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 문서를 참조하십시오 .


내가 한 방법은 다음과 같습니다. 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;
}

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

Mark Baker의 답변에 따라 다음 함수를 작성했습니다.

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

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


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

This can also be done like this:

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

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

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

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

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

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;

You can directly using Carbon

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

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

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

ReferenceURL : https://stackoverflow.com/questions/31849334/php-carbon-get-all-dates-between-date-range

반응형