PHP setlocale has no effect

For those coming here looking for date() doesn't localize month and weekday names:

== Pay Attention ==

date() is only able to return month/day names in English and won't be able to give you translations for other languages.

Use strftime() instead!


This solution might help if you don't have shell access to the server.

If you have shell access, then Benjamin Seiller's answer is the best!

As I don't have any other possibilities (shell), I've found a solution with only PHP by using the IntlDateFormatter class.

<?php

// Example vars
$month = '6';
$year = '2014';

$fmt = new IntlDateFormatter('de_DE',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'Europe/Berlin',
    IntlDateFormatter::GREGORIAN);

$lastMonth = mktime(0, 0, 0, $month -1, 1, $year);

$showLastMonth =  $fmt->format($lastMonth);
echo $showLastMonth;

Your code is correct. You probably just have to install the correct language package on the server you are running the script on.

In the terminal, if the language you want to use is not listed after running the command sudo locale -a, then you'll have to install the missing language by running the following command :

sudo /usr/share/locales/install-language-pack de_DE 

(sudo here is optional if your user has root permissions)

Then if you double check with sudo locale -a you should see de_DE.utf8.

If you want to install french language package run

sudo /usr/share/locales/install-language-pack fr_FR

Then you'll be allowed to set your language to these in PHP by using setlocale(...) exactly like you did it.


Note: If you are in a non utf8 project you'll need to generate other formats from installed packages. Here is how to proceed on ubuntu (this work on debian as well) :

edit /var/lib/locales/supported.d/cs and add the following lines

  fr_FR.iso88591 ISO-8859-1
  fr_CA.iso88591 ISI-8859-1

and run

 sudo dpkg-reconfigure locales

Then by running again sudo locale -a you should see both fr_FR.iso88591 and fr_CA.iso88591 in the list and you can use it in php by calling setlocale(LC_ALL, 'fr_FR.iso88591');


Is is quite likely that the German locale is not installed on the server your running the script on - do you have shell access to the server? Then try

locale -a

to see which locales are installed. Also have a look here Is it feasible to rely on setlocale, and rely on locales being installed?