RichardMiracles
RichardMiracles

Reputation: 2152

Use Carbon PHP to format a date

I received this date of my database: 2017-02-06T22:25:12Z

I tried formatting it with Carbon php:

{{ \Carbon\Carbon::createFromFormat('Y-m-d H', '2017-02-06T22:25:12Z')->toDateTimeString() }}

But this not works, I want this date format: 06-02-17 22:25:12

Upvotes: 2

Views: 19000

Answers (2)

Christophvh
Christophvh

Reputation: 13224

If you add dates to your migration, be sure to mutate them on your model.

So on your model add the following:

/**
 * The attributes that should be mutated to dates.
 *
 * @var array
 */
protected $dates = [
    'your_date'
];

https://laravel.com/docs/5.4/eloquent-mutators#date-mutators

If you mutate your date, it becomes a Carbon instance, which means you can use all carbon formatting tools.

From the docs:

By default, timestamps are formatted as 'Y-m-d H:i:s'. If you need to customize the timestamp format, set the $dateFormat property on your model. This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON.

So if you would like to change the formatting everywhere use $dateFormat on your model like so:

 protected $dateFormat = 'd-m-y H:i:s';

If you only want to format your date inside your view , you can do it like so:

{{ $your_date->format('d-m-y H:i:s') }}

For more advanced formatting you can take a look at the carbon docs: http://carbon.nesbot.com/docs/

Upvotes: 1

Spholt
Spholt

Reputation: 4012

You can use the parse method to get a quick and dirty conversion

Carbon::parse('2017-02-06T22:25:12Z')->format('d-m-y H:i:s');

If you are using a model to return this date you could also look at making it return as a Carbon object by adding it to the protected $dates[] array

Upvotes: 9

Related Questions