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

前端 未结 6 839
既然无缘
既然无缘 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:10

    When you retrieve a date off a model in Laravel, you get back a Carbon object: https://github.com/briannesbitt/Carbon

    If you refer to the Carbon documentation, it tells you how you can get a locale formatted Date:

    Unfortunately the base class DateTime does not have any localization support. To begin localization support a formatLocalized($format) method has been added. The implementation makes a call to strftime using the current instance timestamp. If you first set the current locale with setlocale() then the string returned will be formatted in the correct locale.

    setlocale(LC_TIME, 'German');                     
    echo $dt->formatLocalized('%A %d %B %Y');          // Donnerstag 25 Dezember 1975
    setlocale(LC_TIME, '');                           
    echo $dt->formatLocalized('%A %d %B %Y');          // Thursday 25 December 1975
    

    So basically, just use formatLocalized('M') instead of format('M')

提交回复
热议问题