DEV Community

Techsolutionstuff
Techsolutionstuff

Posted on • Originally published at techsolutionstuff.com

Carbon diffForHumans Laravel Example

Today we will see carbon diffForHumans laravel example, this function in carbon provides human readable date and time formate in laravel or php.

When we want to display a date in the past with reference to the current time then you can use diffforhumans() carbon function, using diffforhumans carbon we can get results like this A few seconds ago, 30 minutes ago, 2 days ago, 1 year ago.

Example:

$post->created_at->diffForHumans() //output : 2 hours ago
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)