I’ve spent like the last 30 minutes searching the web for how to convert dates to human-readable strings with Carbon in PHP/Laravel. Here’s a compilation of a couple of useful Carbon methods for my future self.
Formatting Examples
<?php
$date = Carbon::now();
echo $date->toDateString();
// 2020-06-22
echo $date->toDateTimeString();
// 2020-06-22 19:45:23
echo $date->toFormattedDateString();
// Jun 22, 2020
echo $date->toTimeString();
// 19:45:23
echo $date->toDayDateTimeString();
// Mon, Jun 22, 2020 7:45 PM
echo Carbon::now()->subDays(5)->diffForHumans();
// 5 days ago
echo Carbon::now()->subDays(24)->diffForHumans();
// 3 weeks ago
echo Carbon::now()->subMonth()->diffForHumans();
// 1 month ago
echo Carbon::create('2020')->longRelativeDiffForHumans('2018');
// 5 months 3 weeks 19 hours 40 minutes 54 seconds ago
Further Reading
There’s plenty more, have a look at the links below.