【问题标题】:Change Laravel DataTables time format更改 Laravel DataTables 时间格式
【发布时间】:2020-11-08 21:41:28
【问题描述】:

在我的订单表中,created_at 列以这种格式保存:Y-m-d H:i:s

但是在数据表中,是这样显示的。

我将此代码添加到 Order 模型中:

public function getCreatedAtAttribute($date)
{
    return is_null($date)
        ? ''
        : Carbon::createFromFormat('Y-m-d H:i:s', $date)->timezone(config('app.timezone'))->toDateTimeString();
}

public function getUpdatedAtAttribute($date)
{
    return is_null($date)
        ? ''
        : Carbon::createFromFormat('Y-m-d H:i:s', $date)->timezone(config('app.timezone'))->toDateTimeString();
}

但是在这之后,数据表不起作用并返回以下错误:

DataTables 警告:表 id=DataTables_Table_0 - Ajax 错误。有关此错误的更多信息,请参阅http://datatables.net/tn/7

我该如何解决?

【问题讨论】:

  • 你试过cast吗?

标签: php laravel laravel-7


【解决方案1】:

有很多方法可以做到这一点,你可以从你的控制器中做到这一点:

return Datatables::of($query)
  ->addColumn('created_at', function ($row){
       return $row->created_at->format('d-M-Y');
})

替代方案:在 Eloquent 模型上使用 toArray 或 toJson 方法时,Laravel 7 使用了新的日期序列化格式。 以前,日期会被序列化为如下格式:

2020-12-02 20:01:00

使用 ISO-8601 格式序列化的日期将如下所示:

2020-12-02T20:01:00.283041Z

如果您想继续使用以前的行为,您可以覆盖模型上的 serializeDate() 方法:

use DateTimeInterface;

protected function serializeDate(DateTimeInterface $date)
{
    return $date->format('Y-m-d H:i:s');
}

查看官方升级文档here

【讨论】:

    【解决方案2】:

    DateTime 可以做到这一点

    
    
    $customDate='2020-12-02T20:01:00.283041Z';
    
    $date=new DateTime($customDate);
    
    echo $date->format('y-m-d H:i:s');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多