Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 323
arvil Avatar asked Sep 01 '15 21:09

arvil


2 Answers

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"
like image 151
baao Avatar answered Sep 18 '22 00:09

baao


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.

like image 25
Miracool Avatar answered Sep 22 '22 00:09

Miracool