How to extract the time from "created_at" with Carbon

sesc360 picture sesc360 · Feb 6, 2017 · Viewed 23.8k times · Source

I am struggling with the Carbon functionalities within Laravel framework still. I created these functions used in my model to extract the date of the "created_at" field in my tables:

public function getCreatedAtAttribute($date) {
    return Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('d.m.Y');
}

This works fine for the date, but how would I need to write a function in this model, that will extract only the time within the created_at field?

Answer

Rwd picture Rwd · Feb 6, 2017

I feel like you're limiting yourself a lot be overriding the default behaviour for dates.

If you remove your accessor (getCreatedAttribute) you'll be able to call format from the property itself i.e.

$model->created_at->format('d.m.Y')

or

$model->created_at->format('H:i:s');//e.g. 15:30:00

Carbon is just a wrapper for DateTime. For a list of format characters you can look here: http://php.net/manual/en/function.date.php e.g. todays date as 6th February 2016 would be jS F Y

Hope this helps!