Gam*_*mer 5 php laravel php-carbon laravel-5
我们怎样才能瘦下来diffForHumans()?
Like$post->created_at->diffForHumans()返回前一段时间 Like 3 days agoor 57 minutes ago, or 2 hours ago。
我们怎样才能返回57 mins ago或1W ago等等。
有什么办法吗?
四处寻找,却一无所获。
Carbon 通过魔术方法实现了不同的调用时间配置。可能的配置范围记录在backing trait 中。通过这些方法扫描,看起来你想要shortRelativeDiffForHumans:
$c = new Carbon\Carbon('now -1 day 4 hours');
dump($c->diffForHumans(), $c->shortRelativeDiffForHumans());
"20 hours ago"
"20h ago"
Run Code Online (Sandbox Code Playgroud)
如果失败,您可以使用str_replace或 类似的字符串函数来调整结果值。
我会注意到,为了回应@Giovanni 的贡献,这些魔法方法只是对diffForHumans. 我更喜欢这些较长的方法名称及其变体,因为它们是自我记录的。一年后扫描代码时,使用的diffForHumans第三个参数true并没有告诉我太多!
传递给 diffForHumans() 的第三个值用于缩短显示输出。
尝试类似的东西,
$post->created_at->diffForHumans(null, false, true)
Run Code Online (Sandbox Code Playgroud)
在这里您可以看到 diffForHumans() 的注释及其接受的值。
/**
* Get the difference in a human readable format in the current locale.
*
* When comparing a value in the past to default now:
* 1 hour ago
* 5 months ago
*
* When comparing a value in the future to default now:
* 1 hour from now
* 5 months from now
*
* When comparing a value in the past to another value:
* 1 hour before
* 5 months before
*
* When comparing a value in the future to another value:
* 1 hour after
* 5 months after
*
* @param Carbon|null $other
* @param bool $absolute removes time difference modifiers ago, after, etc
* @param bool $short displays short format of time units
* @param int $parts displays number of parts in the interval
*
* @return string
*/
public function diffForHumans($other = null, $absolute = false, $short = false, $parts = 1)
{
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5166 次 |
| 最近记录: |