简体   繁体   English

Laravel中不错的上下文日期格式

[英]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". 我想以一种友好的方式在laravel中为用户设置日期格式,例如省略日期,如果消息是今天发送的,或者消息是在上周发送的,只是说“昨天”,“两天前”。

I work with laravel and I'm astonished by the amount of functionalities available out of the box. 我与laravel合作,对开箱即用的功能感到惊讶。 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. 与Laravel捆绑在一起的Carbon包一样,别无所求。

The docs can be found here: http://carbon.nesbot.com/docs/ 可以在以下位置找到该文档: http : //carbon.nesbot.com/docs/

You can find some more human readable output mentioned here: http://carbon.nesbot.com/docs/#api-humandiff 您可以找到此处提到的更多可读的输出: 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. Laravel使用Carbon库。 Here http://carbon.nesbot.com/docs/ you can see a lot of examples, like: $yesterday = Carbon::yesterday(); http://carbon.nesbot.com/docs/上,您可以看到很多示例,例如:$ y​​esterday = Carbon :: yesterday(); echo $yesterday; 回声昨天

If you want to use it in your Eloquent model you can do this in model class: 如果要在Eloquent模型中使用它,可以在模型类中执行此操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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