laravel carbon 从集合的日期列中获取日期名称

laravel carbon get day names from a date column from a collection

我从数据库中获得了这个集合,其中有一列名为 "event_date"。

我想要的只是从集合中的那一列中获取日期名称。

我知道您可以使用 Carbon 来获取名称天数,例如,一个名为 ->format() 的方法,但是我收到一条错误消息,指出此方法不存在。

到目前为止我的代码如下:

$collection = MyModel::all();

里面有 "event_date" 属性 或列。由此,我想获取日期的名称,将它们放入数组或集合中,最后计算这些日期的频率。

为了实现这一点,我尝试了以下方法:

我尝试了->pluck()方法如下:

$filtered = collect([
            'myDates'=>$collection->pluck('event_date'),
        ]);

dd($filtered) 如下所示:

Collection {#209 ▼
  #items: array:1 [▼
    "myDates" => Collection {#243 ▼
      #items: array:30 [▼
        0 => Carbon {#244 ▼
          +"date": "2017-02-05 00:00:00.000000"
          +"timezone_type": 3
          +"timezone": "America/Mexico_City"
        }
        1 => Carbon {#218 ▼
          +"date": "2017-01-15 00:00:00.000000"
          +"timezone_type": 3
          +"timezone": "America/Mexico_City"
        }
        2 => Carbon {#250 ▼
          +"date": "2016-09-25 00:00:00.000000"
          +"timezone_type": 3
          +"timezone": "America/Mexico_City"
        }
        3 => Carbon {#249 ▼
          +"date": "2016-05-22 00:00:00.000000"
          +"timezone_type": 3
          +"timezone": "America/Mexico_City"
        }
...

我尝试按如下方式获取日期名称:

$Daynames = $filtered->each(function($item,$key){
            return $item->myDates->format('l');
        });

但是我得到以下错误:

Undefined property: Illuminate\Support\Collection::$myDates

有什么想法可以只将日名放入数组或集合中吗?还有其他方法吗?

您正在对日期集合调用 format(),而您应该对 Carbon 对象调用它。您需要另一个循环遍历 myDates 集合中的所有日期并格式化它们,例如:

$Daynames = [];
$filtered->each(function($item,$key) use (&$Daynames) {
  $item->each(function($date) use (&$Daynames) {
    $Daynames[] = $date->format('l');
  });
});

使用收集管道实现此目的的好方法:

$days = MyModel::all()->pluck('event_date')->map(function($date) {
    return $date->format('l');
}); 

通过Carbon库,我们可以轻松获取。

  1. 使用库

    use Carbon\Carbon;
    
  2. 获取日期

    $date = '2018-11-15';
    $d    = new DateTime($date);
    $d->format('l');  //pass l for lion aphabet in format 
    

输出为 Thursday。 它在 laravel

对我有用
  1. 使用库

    use Carbon\Carbon;

  2. 解析日期

    $day = Carbon::parse($yourDate)->format('l')

你可以用不止一种方式来处理

Carbon::parse($date)->dayName; // Monday ... 

Carbon::parse($date)->format('l'); // Monday ... 

自定义位置

Carbon::parse($date)->locale('fr')->dayName;// Lundi ...