How can we trim down diffForHumans()
?
Like $post->created_at->diffForHumans()
return the time ago Like 3 days ago
or 57 minutes ago
, or 2 hours ago
.
How can we be able to return 57 mins ago
or 1W ago
etc.
Is there any way around ?
Searched around but got nothing.
The third value passed to diffForHumans() is for shortening the display output.
Try something like,
$post->created_at->diffForHumans(null, false, true)
here you can see a the comments for diffForHumans() and the values it accepts.
/**
* 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)
{
Carbon implements different call-time configurations through magic methods. The universe of possible configurations are documented in the backing trait. Scanning through those methods, it looks like you want shortRelativeDiffForHumans
:
$c = new Carbon\Carbon('now -1 day 4 hours');
dump($c->diffForHumans(), $c->shortRelativeDiffForHumans());
"20 hours ago"
"20h ago"
Failing that, you can use str_replace
or similar string functions to adjust the resulting value.
I'll note, in response to @Giovanni's contribution, that these magic methods are just verbose wrappers around the call to diffForHumans
. I prefer these longer method names and their variations, because they're self-documenting. Using diffForHumans
third argument of true
doesn't tell me much when scanning code a year later!
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