Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Carbon to return a human readable datetime difference

I'm using Laravel 4 to create my project.

I am currently building the comments section and I want to display how long ago the post was created, kind of like Facebook's '10 mins ago' & '2 weeks ago' etc.

I have done a little bit of research and found that a package called Carbon can do this.

After reading the Laravel doc's, it says:

By default, Eloquent will convert the created_at, updated_at, and deleted_at columns to instances of Carbon, which provides an assortment of helpful methods, and extends the native PHP DateTime class.

But when I return a date column that I have created, it doesn't display it like on Facebook.

The code that I'm using is:

return array('time'); 

Has any body used this Carbon package that could give me a hand in doing what I need, I'm quite confused.

like image 860
BigJobbies Avatar asked Jun 23 '13 11:06

BigJobbies


People also ask

How do you find the difference between two dates in carbon?

You can only use the diffInDays() function on a Carbon instance. You can create a new one by parsing the end date you're receiving. $end = Carbon::parse($request->input('end_date'));

What does carbon :: now () return?

Carbon::now returns the current date and time and Carbon:today returns the current date. This is a sample output.

How do you use carbon in laravel blade?

If you want to use the namespaced class, you don't need the first slash: $create_at_difference=Carbon\Carbon::createFromTimestamp(strtotime($create))->diff(\Carbon\Carbon::now())->days; You should just write Carbon\Carbon instead of \Carbon\Carbon. That is a quick solution.


1 Answers

By default, Eloquent will convert the created_at, updated_at, and deleted_at columns to instances of Carbon. So, your code should be just like this:

$comment->created_at->diffForHumans(); 

It's very cool. It'll produce string like 2 minutes ago or 1 day ago. Plurar or singular, seconds, minutes, hours, days, weeks, or years, it runs automatically. I've tested it on Laravel version 4.1.24.

like image 159
Ifan Iqbal Avatar answered Sep 27 '22 22:09

Ifan Iqbal