简体   繁体   中英

Nice, contextual date formatting in laravel

I'm making simple mailing application. I wanted to format date in laravel for the user in a friendly way, such as omitting date, if the message was sent today, if it was sent in last week to just say "yesterday", "2 days ago".

I work with laravel and I'm astonished by the amount of functionalities available out of the box. Is there already such functionality or do I have to code it myself?

Yes! Look no further than the Carbon package that is bundled with Laravel.

The docs can be found here: http://carbon.nesbot.com/docs/

You can find some more human readable output mentioned here: http://carbon.nesbot.com/docs/#api-humandiff

To use carbon just import it into one of your classes like this:

use Carbon\Carbon;

$date = Carbon::createFromDate(2012, 1, 1, 'Europe/London');

Laravel uses Carbon library. Here http://carbon.nesbot.com/docs/ you can see a lot of examples, like: $yesterday = Carbon::yesterday(); echo $yesterday;

If you want to use it in your Eloquent model you can do this in model class:

public function readableTime()
{
    return $this->created_at->diffForHumans();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM