I have recently been using Carbon to display humanized time strings, but for some reason I can only get it to show the main factor, for example, I have a date that it needs to show how long until that date is. So for example, if its 6 days, 4 hours and 32 minutes away from now, it currently only displays '6 days'.
How would I go about getting it to display the hours too, and possibly the minutes? It's kind of horrible looking when it only gives you the days, and many people may want to know more like the hours and seconds?
I can't find anything on the Carbon documentation for this. I am using it inside a laravel 5.3 view if that's even relevant.
Heres my code:
{{ \Carbon\Carbon::createFromTimeStamp(strtotime($item->created_at))->diffForHumans() }}
You shouldn't use diffForHumans()
in this case, because it returns only a string on which one can no longer work. This is an end result.
It is better to work with a Carbon
object, like this :
$created = \Carbon\Carbon::createFromTimeStamp(strtotime($item->created_at));
And then, add this in the view :
{{ $created ->diff(\Carbon\Carbon::now())->format('%d days, %h hours and %i minutes'); }}
You can extend for a larger period :
$created ->diff(\Carbon\Carbon::now())->format('%y year, %m months, %d days, %h hours and %i minutes');
EDIT (according to the comments) :
If you do :
$diff = $created->diff(Carbon::now());
var_dump($diff);
You get this result :
object(DateInterval)[113]
public 'y' => int 0
public 'm' => int 0
public 'd' => int 6
public 'h' => int 4
public 'i' => int 32
public 's' => int 29
public 'f' => float 0.397424
public 'weekday' => int 0
public 'weekday_behavior' => int 0
public 'first_last_day_of' => int 0
public 'invert' => int 0
public 'days' => int 6
public 'special_type' => int 0
public 'special_amount' => int 0
public 'have_weekday_relative' => int 0
public 'have_special_relative' => int 0
// results depend of the current time
From there, you browse the elements to create the best answer to your needs.
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