【问题标题】:How to convert a carbon into string, to take the date only?如何将碳转换为字符串,仅获取日期?
【发布时间】:2018-11-14 11:19:18
【问题描述】:

我有这样的收藏

0 => array:4 [
  "so" => "SO-1"
  "product_name" => "EXTREME FORTE - BP"
  "created_at" => Carbon @1527481346 {#628
    date: 2018-05-28 04:22:26.0 UTC (+00:00)
  }
  "id" => "5b0b84027475aa1508002623"
]

如何只取“2018-05-28”? 有人可以帮我解决这个问题吗?还是谢谢

【问题讨论】:

标签: php laravel collections php-carbon


【解决方案1】:

也可以为您的模型添加自动铸造,例如:

protected $casts = [
    'created_at' => 'date:Y-m-d',
    'updated_at' => 'datetime:Y-m-d H:00',
];

备注:您的里程可能会因您的 Laravel 版本而异

https://laravel.com/docs/8.x/eloquent-mutators#date-casting

https://laravel.com/docs/8.x/eloquent-serialization#date-serialization

【讨论】:

    【解决方案2】:

    我更喜欢这个

    $model_item->created_at->toDateString();
    

    因为模态中位于protected $dates array 中的所有日期字段都是\Carbon\Carbon 的类型。

    所以上面的代码可以应用于任何日期字段,只要您在模态中将其声明为$dates array 中的日期 如下

    // this includes created_at and updated_at by default so no need to add it 
    protected $dates = ['approved', 'seen_at'];
    

    【讨论】:

      【解决方案3】:
      $collection_item->created_at->format('Y-m-d');
      

      【讨论】:

      猜你喜欢
      • 2015-12-09
      • 2019-06-14
      • 1970-01-01
      • 1970-01-01
      • 2018-07-08
      • 2020-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多