Today, we will explore the Carbon diffForHumans
function in Laravel, which allows us to display human-readable date and time formats. This feature comes in handy when you need to show dates in relation to the current time, providing results such as "A few seconds ago," "30 minutes ago," "2 days ago," or "1 year ago."
This article will provide examples and insights into using diffForHumans
in Laravel 8, 9, and 10, making your date and time displays more user-friendly.
Example:
$post->created_at->diffForHumans() //output : 2 hours ago
When we need to compare the value in the future to default now like, 30 minutes from now, 1 hour from now, 2 days from now at that time we need to add days like the below example.
$user->created_at->addDays(2)->diffForHumans() // output : 2 days from now
When we need to compare value in the past to another value like, 30 minutes before, 1 hour before at that time we will use the below example.
$yesterday->diffForHumans($today) // output : 1 day before
When we need to compare value in the future to another value like, 30 minutes after, 1 hour after, 1 day after at that time we will use the below example
$tomorrow->diffForHumans($today) // output : 1 day after
You might also like: