Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the time from "created_at" with Carbon

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?

like image 482
sesc360 Avatar asked Feb 06 '17 15:02

sesc360


People also ask

How does carbon add time?

You can add hours on current date using carbon in laravel 6, laravel 7, laravel 8 and laravel 9 version. If you need to add hour or more hours in date then you can use carbon in laravel. carbon provide addHour() and addHours() method to add hours on carbon date object.

How can I get laravel days?

function dateDiffInDays($date1, $date2) { $diff = strtotime($date2) - strtotime($date1); return abs(round($diff / 86400)); } // Start date $date1 = "2021-03-01 04:03:00"; // End date $date2 = date('Y-m-d'); $dateDiff = dateDiffInDays($date1, $date2);

How do you get a carbon month?

$now = Carbon\Carbon::now(); $month = $now->format('m'); Assuming the current month was January, you would receive '01' from that format call. As an aside, if that's all you're using Carbon for in that class, you could just use the default PHP date() method if you feel like using less dependencies.


2 Answers

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

If you remove your accessor (getCreatedAtAttribute) 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

like image 147
Rwd Avatar answered Sep 18 '22 12:09

Rwd


try to use

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

output will be time

like image 38
Junaid Avatar answered Sep 20 '22 12:09

Junaid