Carbon date language not change on format [duplicate] - php

Ive read several stackoverflows about set locale. I tested locale -a in the terminal to see if my locale was in there, and it was. The following rule of code is added in the appServiceProvider:
public function boot()
{
Carbon::setLocale($this->app->getLocale());
}
The $this->app->getLocale() returns "nl"
Anyone know why Carbon still shows Sunday instead of Zondag for example?

Translating a carbon date using global localized format
Tested in: Laravel 5.8, Laravel 6, Laravel 8
In config/app.php
'locale' => 'id', // The default is 'en', but this time I want localize them to Indonesian (ID)
Then, to make locale output do something like this:
// WITHOUT LOCALE
Carbon\Carbon::parse('2019-03-01')->format('d F Y'); //Output: "01 March 2019"
now()->subMinute(5)->diffForHumans(); // Output: "5 minutes ago"
// WITH LOCALE
Carbon\Carbon::parse('2019-03-01')->translatedFormat('d F Y'); // Output: "01 Maret 2019"
now()->subMinute(5)->diffForHumans(); // Output: "5 menit yang lalu"
For more information about converting localize dates you can see on below link
https://carbon.nesbot.com/docs/#api-localization

You might want to use setLocale(LC_TIME, $this->app->getLocale()) somewhere at the start of your application.
Then if you wish to have the localized date format with local names use the formatLocalized function
Carbon::now()->formatLocalized('%d %B %Y');
See http://php.net/manual/en/function.strftime.php for parameter for formatting

Researching I have found two alternative options:
$date = Carbon::now();
$date->locale('de')->translatedFormat('d F Y');
and:
$date = Carbon::now();
$carbonDateFactory = new CarbonFactory([
'locale' => 'de_DE',
'timezone' => 'Europe/Paris',
]);
$carbonDateFactory->make($date)->isoFormat('d MMMM YYYY');
and the ISO compatible format symbols are here

I solved this by calling setLocale on multiple classes:
$locale = 'nl_NL';
\Carbon\Carbon::setLocale($locale);
\Carbon\CarbonImmutable::setLocale($locale);
\Carbon\CarbonPeriod::setLocale($locale);
\Carbon\CarbonInterval::setLocale($locale);
\Illuminate\Support\Carbon::setLocale($locale);
There's also this ServiceProvider that does the same.

In your AppServiceProvider's register function:
setlocale(LC_TIME, 'nl_NL.utf8');
Carbon::setLocale(config('app.locale'));
Then use translatedFormat() instead of format() or formatLocalized() which is deprecated.
This uses the date() patern which works like format() but translates the string using the current locale.
read more here and here.

try this : setLocale(LC_TIME, app()->getLocale());

Related

Carbon setLocale not working Laravel

Ive read several stackoverflows about set locale. I tested locale -a in the terminal to see if my locale was in there, and it was. The following rule of code is added in the appServiceProvider:
public function boot()
{
Carbon::setLocale($this->app->getLocale());
}
The $this->app->getLocale() returns "nl"
Anyone know why Carbon still shows Sunday instead of Zondag for example?
Translating a carbon date using global localized format
Tested in: Laravel 5.8, Laravel 6, Laravel 8
In config/app.php
'locale' => 'id', // The default is 'en', but this time I want localize them to Indonesian (ID)
Then, to make locale output do something like this:
// WITHOUT LOCALE
Carbon\Carbon::parse('2019-03-01')->format('d F Y'); //Output: "01 March 2019"
now()->subMinute(5)->diffForHumans(); // Output: "5 minutes ago"
// WITH LOCALE
Carbon\Carbon::parse('2019-03-01')->translatedFormat('d F Y'); // Output: "01 Maret 2019"
now()->subMinute(5)->diffForHumans(); // Output: "5 menit yang lalu"
For more information about converting localize dates you can see on below link
https://carbon.nesbot.com/docs/#api-localization
You might want to use setLocale(LC_TIME, $this->app->getLocale()) somewhere at the start of your application.
Then if you wish to have the localized date format with local names use the formatLocalized function
Carbon::now()->formatLocalized('%d %B %Y');
See http://php.net/manual/en/function.strftime.php for parameter for formatting
Researching I have found two alternative options:
$date = Carbon::now();
$date->locale('de')->translatedFormat('d F Y');
and:
$date = Carbon::now();
$carbonDateFactory = new CarbonFactory([
'locale' => 'de_DE',
'timezone' => 'Europe/Paris',
]);
$carbonDateFactory->make($date)->isoFormat('d MMMM YYYY');
and the ISO compatible format symbols are here
I solved this by calling setLocale on multiple classes:
$locale = 'nl_NL';
\Carbon\Carbon::setLocale($locale);
\Carbon\CarbonImmutable::setLocale($locale);
\Carbon\CarbonPeriod::setLocale($locale);
\Carbon\CarbonInterval::setLocale($locale);
\Illuminate\Support\Carbon::setLocale($locale);
There's also this ServiceProvider that does the same.
In your AppServiceProvider's register function:
setlocale(LC_TIME, 'nl_NL.utf8');
Carbon::setLocale(config('app.locale'));
Then use translatedFormat() instead of format() or formatLocalized() which is deprecated.
This uses the date() patern which works like format() but translates the string using the current locale.
read more here and here.
try this : setLocale(LC_TIME, app()->getLocale());

How get a day with a carbon by German in Laravel?

How get a day with a carbon by German in Laravel?
Try:
return $item->formatLocalized('%A, %d.%m.%Y %H:%M');
Need:
Montag, 17.04.2017 10:00
Did you put this on bootstrap/app.php
setlocale(LC_TIME, 'German');
Today (with Laravel 9) the answer is:
set your desired locale in config/app.php
with that use translatedFormat instead of format.
Carbon::parse($string)->translatedFormat($format)

Change date format Laravel

I'm from Indonesia, and I want to show date with Indonesian language format but what I've got was English language format.
Example format was 23 march 2017 (english)
I want to get like this one 23 Maret 2017 (Indonesia) so the problem of mine is language.
Can you give me some idea ? this is my example code
<?php echo date("d F Y", strtotime($row->tanggal_pelaksanaan)); ?>
and
Tgl: #foreach ($tindak as $tindakan)
{{ date("d F Y", strtotime($tindakan->target_verifikasi)) }}
#endforeach
Please Kindly help me. thank you.
See if the locale is installed in your server.
You can list all the locale in your server by issuing the command
locale -a
Install your locale. Indonesian locale, I believe is id_ID by issuing the command. The list of locale is obtained from this answer https://stackoverflow.com/a/28357857/5808894
sudo locale-gen id_ID
sudo update-locale
Set locale using the method setlocale
setlocale(LC_TIME, 'id_ID');
Either use Carbon or strftime to output the localized date
strftime("%a %d %b %Y", strtotime(date('Y-m-d')))
OR
Carbon\Carbon::parse('23-03-2017 11:23:45')->formatLocalized('%A %d %B %Y');
outputs Kamis 23 Maret 2017
$dateName = Carbon::now()->locale('id')->isoFormat('LL'); //return 17 Mei 2020
$dateName = Carbon::now()->locale('id')->isoFormat('LLLL'); //return Minggu, 17 Mei 2020 pukul 10.21
Try this code
and you can check on https://carbon.nesbot.com/docs/#api-localization
Laravel Eloquent allows you format from the model so you can do
$model->created_at->format('Y-m-d')
To do this you should add
$protected $dates = [
'created_at',
'updated_at',
// add other column names here that you want as Carbon Date
];
This will then mutate the columns to be a easily manipulated date object
see https://laravel.com/docs/5.4/eloquent-mutators#date-mutators for further details
You cannot depends on server locale, because most of application was running on their own devices with their own locale format. You can installing the locale format for your own device but not for others because they have their locale timezone.
Use another method like:
{{ date('d-m-y', strtotime($example->start_date))}}
The code above will change
yyyy-mm-dd
format to
d-m-y
2019-05-01 to 01-05-19
Or
{{ date('l, d-m-y', strtotime($example->start_date))}}
Ouput:
Friday, 01-05-2019
Hope it helps.

Php mysql date in table

I have a date field in my table material
id: int;
dat_operation : date;
name : varchar(255);
I would like to know how to translate date format in French
I tried with:
<?php echo date("F j Y",strtotime($var['date_operation']));?>
But i have this result
June 14 2016
First, you'll have to set the "locale information", to specify which language you want to use. Keep in mind, that even though you set that language, it needs to be installed on the server you're running on. It most likely is, but you'll notice if the setlocale has no effect (default is English).
The second thing you'll need to know, is that date() isn't affected by this, you'll have to use strftime() instead, which has a slightly different formatting, which you'll find on the documentation.
An example of using French dates with these two functions:
setlocale(LC_ALL, 'fr_FR');
echo strftime("%B %e %Y", strtotime($var['date_operation']));
Reference and documentation:
http://php.net/manual/en/function.setlocale.php
http://php.net/manual/en/function.strftime.php
The modern and rock-solid approach is the intl (from "Internationalization") extension, which offers e.g. the IntlDateFormatter class:
$date = new DateTime('2016-06-14');
$fmt = new IntlDateFormatter('fr_FR', IntlDateFormatter::LONG, IntlDateFormatter::NONE, 'Europe/Paris', IntlDateFormatter::GREGORIAN);
var_dump($fmt->format($date));
string(12) "14 juin 2016"
If you think it's overkill for your project, you can use the legacy strftime() function but you need to change current locale:
$date = strtotime('2016-06-14');
var_dump(setlocale(LC_TIME, 'fr_FR', 'fr')); // Need to try values until you get true
var_dump(strftime('%B %e %Y', $date));
You need to have French locale data installed. In my experience, this works better on Unix-like systems than on Windows.

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

Take this example:
{{ $article->created_at->format('M') }}
It returns Nov. I need to localise this to my language, so the output should be Kas
Thought about doing the following:
{{ trans("language.{$article->created_at->format('M')}") }}
app/lang/tr/language.php -> 'nov' => 'kas'
This looks like reinventing the wheel and programmatically pretty terrible. I'm sure there are some localisation standards. Something like:
{{ $article->created_at->format('M')->localiseTo('tr_TR') }}
What's the best way to achieve this?
Using a library as Laravel-Date you will just need to set the language of the app in the Laravel app config file and use its functions to format the date as you want.
Set the language in /app/config/app.php
'locale' => 'es',
I've found this library pretty useful and clean. To use it, you can write something like the example in the library readme file. I leave the results in spanish.
echo Date::now()->format('l j F Y H:i:s'); // domingo 28 abril 2013 21:58:16
echo Date::parse('-1 day')->diffForHumans(); // 1 día atrás
This is the link to the repository:
https://github.com/jenssegers/laravel-date
To install this library you can follow the instructions detailed in the following link:
https://github.com/jenssegers/laravel-date#installation
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')
As of carbon version 2.30.0, you can use the translatedFormat function
$date = Carbon::parse('2021-12-08 11:35')->locale('pt-BR');
echo $date->translatedFormat('d F Y'); // 08 dezembro 2021
It is also a good idea to set locale globally for each request (eg. in filters.php) when using Carbon date instances.
App::before(function($request) {
setlocale(LC_TIME, 'sk_SK.utf8');
});
and then proceed as usual
$dt->formatLocalized('%b'); // $dt is carbon instance
See format options here and list of locales here.
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.
Goto your App->Config->app.php
put
'timezone' => 'Asia/Kolkata',
use simple {{$post->created_at->diffForHumans()}}
Localized (i18n) date with Laravel 8
In Laravel 8, I added a method in my Block Model:
use Illuminate\Support\Carbon;
class Block extends Model
{
public function updatedDate() {
return Carbon::parse($this->updated_at)->translatedFormat('d F Y');
}
}
In my Blade template, I want to get the latest row's update date:
{{ $blocks->last()->updatedDate() }} // prints out 25 January 2022
// PS. Carbon uses your app.locale config variable so setting locale() is optional
// return Carbon::parse($this->updated_at)->locale('en')->translatedFormat('d F Y')
I guess you should consult setlocale manpage. Though Im not sure if Laravel has any wrapper on it.

Categories