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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.