PHP Carbon, get all dates between date range?

匿名 (未验证) 提交于 2019-12-03 02:45:02

问题:

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

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

回答1:

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

$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 $to before generating the DatePeriod

$interval = new DateInterval('P1D'); $daterange = new DatePeriod($from, $interval ,$to);  foreach($daterange as $date){     echo $date->format("Ymd"), PHP_EOL; } 


回答2:

Here's how I did it with Carbon

private function generateDateRange(Carbon $start_date, Carbon $end_date) {     $dates = [];      for($date = $start_date; $date->lte($end_date); $date->addDay()) {         $dates[] = $date->format('Y-m-d');     }      return $dates; } 


回答3:

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

/**  * 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.



回答4:

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


回答5:

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


回答6:

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; 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!