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!
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"
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.
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