To format a date as a relative time using Carbon in PHP, you can use the diffForHumans()
method provided by Carbon.
Here's an example of how you can format a date as a relative time:
use Carbon\Carbon;
// Create a new Carbon instance with the desired date and time
$dateTime = Carbon::parse('2022-06-06 20:00:00');
// Get the relative time using diffForHumans() method
$relativeTime = $dateTime->diffForHumans();
echo $relativeTime; // Output: "2 hours ago"
In the example above, we first create a new instance of Carbon using the desired date and time. Then, we use the diffForHumans()
method on that instance to get the relative time. Finally, we display the relative time with the echo
statement.
You can adjust the input date and time as per your requirements, and Carbon will automatically calculate the relative time for you.