What's the best way to localise a date on Laravel?

前端 未结 6 846
既然无缘
既然无缘 2020-12-05 17:34

Take this example:

{{ $article->created_at->format(\'M\') }}

It returns Nov. I need to localise this to my language, so

6条回答
  •  渐次进展
    2020-12-05 18:03

    In addition to the accepted answer, I was looking for a way to use this within Blade using the Carbon instance of created_at for example. The class in the accepted answer didn't seem to accept a Carbon instance as date, but rather parsed a date from a string.

    I wrote a little helper function to shorten the code in the blade templates:

    function localeDate($date, $format)
    {
        return Jenssegers\Date\Date::createFromFormat('d-m-Y H:i:s',  $date->format('d-m-Y H:i:s'))->format($format);
    }
    

    Within Blade you can now use:

    {{ localeDate($model->created_at, 'F') }}
    

    Which would return the fully written name of the month in the locale set in config/app.php

    If there's a better way (or I missed something in the code), please let me know. Otherwise this might be helpfull for others.

提交回复
热议问题