I have an array that returns the following date time:
$item['created_at'] => "2015-10-28 19:18:44"
How do I change the date to M d Y format in Laravel using Carbon?
Currently it returns with an error
$suborder['payment_date'] = $item['created_at']->format('M d Y');
First parse the created_at field as Carbon object.
$createdAt = Carbon::parse($item['created_at']);
Then you can use
$suborder['payment_date'] = $createdAt->format('M d Y');
It easy for Laravel 5 in your Model add property protected $dates = ['created_at', 'cached_at']. See detail here https://laravel.com/docs/5.2/eloquent-mutators#date-mutators
Ex:
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
}
You can format date like this $user->created_at->format('M d Y'); or any format that support by PHP.
If you are using eloquent model (by looking at your code, i think you are), you dont need to convert it into array. Just use it as object. Becaus elike Thomas Kim said, by default it is a Carbon instance
So it should be
$suborder['payment_date'] = $item->created_at->format('Y-m-d')
But if it is not then, you need convert it to Carbon object as Milan Maharjan answer
$createdAt = Carbon::parse($item['created_at']);
Laravel 5 timestamps are instances of Carbon class, so you can directly call Carbon's string formatting method on your timestamps. Something like this in your view file.
{{$task->created_at->toFormattedDateString()}}
Declare in model:
class ModelName extends Model
{
protected $casts = [
'created_at' => 'datetime:d/m/Y', // Change your format
'updated_at' => 'datetime:d/m/Y',
];
$suborder['payment_date'] = Carbon::parse($item['created_at'])->format('M d Y');
Try that:
$createdAt = Carbon::parse(date_format($item['created_at'],'d/m/Y H:i:s');
$createdAt= $createdAt->format('M d Y');
来源:https://stackoverflow.com/questions/33405939/laravel-5-carbon-format-datetime