简体   繁体   English

使用diffForHumans()方法将now()与datetime的碳差异与“之前”相比较

[英]Carbon difference of now() vs datetime with “ago” using diffForHumans() method

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

to get an ago 得到一个ago

When comparing a value in the past to default now 将过去的值与默认值进行比较时

but whatever I do, I cannot get the ago 但不管我做什么,我不能得到的ago

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

results to before , while 结果到before ,而

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

results to after , 结果到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? 但正如你可以清楚地看到我上面的两个片段比较past ($ datetime)和现在的默认值(Carbon :: now())所以我无法理解为什么我不能在以前获得? Hope somebody can help. 希望有人可以提供帮助。 I just need to echo ago . 我只需要呼应ago Thanks! 谢谢!

You should use diffForHumans() without arguments and after the 'date calculation', like: 您应该使用不带参数的diffForHumans()并在'date calculation'之后使用,例如:

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

or, if you have a date, you can just use use $datetime->diffForHumans(); 或者,如果你有一个日期,你可以使用$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 . 虽然@baao给出了一个很好的答案但是如果你传递一个原始日期输入,那么Carbon::createFromDate()函数可能会有问题,比如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. 其中$users->created_at 2018-05-03 14:54:14 $users->created_at是一个像2018-05-03 14:54:14这样的日期,这将给出一个像2周前一样的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM