php - Change Laravel DataTables time format

In my orders table,created_at
column saved in this format :Y-m-d H:i:s
But in the data table, it is displayed like this.
I add this code to the Order model:
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();
}
But after this, the data table doesn't work and returns the following error:
DataTables warning: table id=DataTables_Table_0 - Ajax error. For more information about this error, please see http://datatables.net/tn/7
How can I solve it?
Answer
Solution:
There are a lot of way to do that, you can do it from your controller as :
return Datatables::of($query)
->addColumn('created_at', function ($row){
return $row->created_at->format('d-M-Y');
})
Alternative : Laravel 7 uses a new date serialization format when using the toArray or toJson method on Eloquent models. Previously, dates would be serialized to a format like the following :
2020-12-02 20:01:00
Dates serialized using the ISO-8601 format will appear like :
2020-12-02T20:01:00.283041Z
If you would like to keep using the previous behavior you can override theserializeDate()
method on your model :
use DateTimeInterface;
protected function serializeDate(DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
See the official upgrade doc here
Answer
Solution:
you can that with DateTime
$customDate='2020-12-02T20:01:00.283041Z';
$date=new DateTime($customDate);
echo $date->format('y-m-d H:i:s');
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: a non-numeric value encountered in
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.