Carbon difference of now() vs datetime with "ago" using diffForHumans() method
Asked Answered
P

2

8

According to the manual: http://carbon.nesbot.com/docs/#api-humandiff

to get an ago

When comparing a value in the past to default now

but whatever I do, I cannot get the ago

return $datetime->diffForHumans(Carbon::now())

results to before, while

return Carbon::now()->diffForHumans($datetime);

results to after,

but as you can see clearly both of my snippet above compares the past($datetime) and to default now (Carbon::now()) so I cannot understand why I can't get an ago? Hope somebody can help. I just need to echo ago. Thanks!

Prevail answered 1/9, 2015 at 21:53 Comment(0)
A
12

You should use diffForHumans() without arguments and after the 'date calculation', like:

Carbon::now()->subDays(24)->diffForHumans();  // "3 weeks ago"

or, if you have a date, you can just use use $datetime->diffForHumans(); :

$datetime = Carbon::createFromDate(2015, 8, 25); // or your $datetime of course
return $datetime->diffForHumans();  // "1 week ago"
Albert answered 1/9, 2015 at 23:21 Comment(1)
can you change the "1 week ago" for the date? I want to show the date as soon as the week passed. thank you.Thomajan
V
4

While @baao gave a great answer but the Carbon::createFromDate() function can be problematic if you are passing a raw date input say Laravels created_at. Now you have to use a different function. Take a look below.

$carbondate = Carbon::parse($users->created_at); 
$past = $carbondate->diffForHumans();
dd($past);

Where $users->created_at is a date like 2018-05-03 14:54:14 , This will then give an answer like 2 weeks ago.

Vermin answered 18/5, 2018 at 23:7 Comment(1)
Laravel provides created_at as a Carbon instance, so you can in fact simply call $model->updated_at->diffForHumans();.Mockingbird

© 2022 - 2024 — McMap. All rights reserved.