I have read through the documentation of DiffForHumans
and it’s very straightforward, but is there a way to customize the date to print out:
- 13 Years, 1 Month, 10 Days
- 01 Year, 11 Months, 01 Day
where it will respect the Year/Years, Month/Months, Day/Days?
-
Approach 1:
$date = Carbon::parse('2010-08-29'); $formattedDate = $date->diffForHumans(['parts' => 3, 'join' => ', '];
Will print out
13 years, 1 month, 4 weeks ago
-
Approach 2:
$date = Carbon::parse('2010-08-29'); $formattedDate = $date->diff(now())->format('%y Year, %m Months and %d Days')
Will print out
13 Year, 1 Months and 28 Days
-
Approach 3 (Backup option):
$date = Carbon::parse('2010-08-29'); $formattedDate = $date->diff(now())->format('%y Year(s), %m Month(s) and %d Day(s)')
Will print out
13 Year(s), 1 Month(s) and 28 Day(s)
Is there a vanilla PHP class that could accomplish something similar?
3
Answers
You can skip unit(s) you don’t want:
Side note:
'join' => true
automatically use,
–and
(and translate it if you select another language)That’s the custom function for handling same problem:
You could try this example:
Expected output:
But yes, this example will not cover leading zero and StudlyCase (you could use headline) issues