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?
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.
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);
$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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With