setlocale having no effect in PHP

2019-04-08 05:13发布

问题:

I have the following snippet of code:

setlocale(LC_ALL, "de");
print(strftime("%A %e %B %Y", time()));

and it's printing

Tuesday 4 May 2010

instead of

Dienstag 4. Mai 2010

Any ideas why? How to fix?

回答1:

Do you have the de locale available; what does setlocale return for you? See: return values for setlocale().

Also, check the list of available locales (e.g. locale -a or whatever is suitable for your OS) to see if de is among them. Likely alternatives include de_DE or de_DE.utf8 to name a few.

In Debian, to generate a new locale, run this command:

dpkg-reconfigure locales

and pick the ones you want.



回答2:

Setting the locale will have no effect if the locale is not installed on your system.



回答3:

For me the following did the trick:

setlocale(LC_TIME, "");

In combination with:

echo strftime("%d. %B %Y");

That is how I got the current date in German format. Hope that can help.



回答4:

Try setting LC_ALL to "de_DE". On my system it wouldn't work until I did that.

$ LC_ALL=de date
Tue May  4 07:40:13 CDT 2010
$ LC_ALL=de_DE date
Di 4. Mai 07:39:27 CDT 2010


回答5:

I am using Ubuntu on Raspberry Pi, had the same issue trying to use Portuguese local for date:

setlocale(LC_TIME, "C");
echo strftime("%A");
echo setlocale(LC_TIME, "pt_PT");
echo strftime(" in Portuguese %A");

Then checked with command local -a, pt_PT was not on the list, so I added it sudo /usr/share/locales/install-language-pack pt_PT and run local -a again: there it was pt_PT.utf8. After this, result still the same: output expected for pt_PT still in English. Here is the slight difference that made things work to me:

···
echo setlocale(LC_TIME, "pt_PT.utf8");
···

So, I had to turn pt_PT into pt_PT.utf8



回答6:

locale -a
locale-gen nb_NO.UTF-8
locale-gen nb_NO
update-locale
locale -a
restart php5-fpm


回答7:

maybe you don't have the locale installed so if you are on ubuntu you can check the list with "locale -a" without the cuotes, and check the available languajes in the file /usr/share/i18n/SUPPORTED and them generated the locale required with "locale-gen de_DE"

hope this work for you.



回答8:

Please be aware that you will probably need to restart httpd and php-fpm deamons after generating new locales in Linux.

Without restart php (7.2) couldn't find them, even when listed in locale -a.

Hope it will save someone some time :)



标签: php locale