jenssegers / date

🗓 A library to help you work with dates in multiple languages, based on Carbon.
https://jenssegers.com
MIT License
1.81k stars 244 forks source link

How do i ouput time ago? #54

Closed Ronto closed 9 years ago

Ronto commented 10 years ago

Sorry im a beginner.

I dont know how to output ago with this package

In carbon i use $post->created_at->diffForHumans()

But what every i try here it just throws me an error

kylekatarnls commented 10 years ago

laravel-date extends Carbon so all methods should remain compatible. And laravel-date provides a diffForHumans method with multi-language support.

That should'nt throw error, what is this eror ?

Ronto commented 10 years ago

Problem is if i use it this way

$post->created_at->diffForHumans()

I'ts not working, no translation, it acts like if i would use carbon.

But if i use it like this (just for a test)

echo Date::parse('-1 day')->diffForHumans();

It works fine

Let me be more specific because i think i get the whole thing wrong.

There is an example

echo Date::now(); // 2000-01-31 12:00:00

echo $date->ago(); // 5 days ago

But if i use

{{ $post->created_at->ago() }}

I get an error

Call to undefined method Carbon\Carbon::ago()

kylekatarnls commented 10 years ago

To replace Carbon with Jenssegers\Date\Date, override the asDateTime method in your models:

protected function asDateTime($value) {
    return  new Jenssegers\Date\Date(parent::asDateTime($value));
}

To avoid boilerplate, put it in a abstract class or a trait that all yours models will extends/use.