To set locale to 'de_DE' on my Debian 4 machine I had to:
- uncomment 'de_DE' in file /etc/locale.gen and afterwards
- run locale-gen from the shell
setlocale
(PHP 4, PHP 5)
setlocale — Fija la información de localización (L10n)
Descripción
categoria es una cadena que especifica la categoría de las funciones afectadas por el ajuste de localización:
- LC_ALL para todas las funciones
- LC_COLLATE para la comparación de cadenas, ver strcoll()
- LC_CTYPE para la conversión y clasificación de caracteres, como por ejemplo strtoupper()
- LC_MONETARY para localeconv()
- LC_NUMERIC para el separador decimal (vea también localeconv())
- LC_TIME para el formateo de fecha y hora con strftime()
Note: Desde la versión de PHP 4.2.0, está obsoleto la opción de indicar el parámetro categoria como una cadena, por lo que deben emplearse las constantes mostradas anteriormente. Si se pasa como una cadena (con comillas), se mostrará un mensaje de aviso.
Si localizacion es NULL o una cadena vacía "", los nombres localizados se fijarán a partir de las variables de entorno con los mismos nombres de las categorías anteriores, o desde "LANG".
Si la localizacion es "0" (cero) o no se modifica la configuración de localización, sólo se devuelve la configuración actual.
Si localizacion es un array o va seguido de más parámetros, entonces cada elemento del array o cada parámetro se intenta establecer como nueva configuración de localización hasta que la función tenga éxito. Este modo de funcionamiento es útil cuando una configuración de localización se conoce con diferentes nombres en sistemas diferentes o para brindar la posibilidad de elegir una localización en caso de que falle la localización principal.
Note: La posibilidad de indicar varias configuraciones de localización está disponible desde la versión de PHP 4.3.0
La función devuelve la nueva localización establecida o FALSE si no existe la posibilidad de ajustar la localización o si la localización indicada no existe en el sistema o si el nombre de la categorí no es válido. Un nombre incorrecto de categoría tambié genera un mensaje de aviso. Los nombres de categorías y localizaciones se pueden encontrar en el » RFC 1766 y en » ISO 639. Cada sistema cuenta con su propio esquema de nombres para las localizaciones.
Note: El valor devuelto por setlocale() depende del sistema en el que se esté ejecutando PHP, ya que devuelve exactamente lo mismo que lo que devuelve la función setlocale del sistema en el que se ejecuta.
La información de localización se guarda a nivel de proceso, no de hilo de ejecución. Si se ejecuta PHP en un entorno de ejecución multi-hilo como IIS o Apache sobre Windows, puede que se produzcan cambios repentinos en los ajustes de la localización mientras se está ejecutando el script (incluso si el script no hace uso de la función setlocale()). Estos cambios se producen por el hecho de que otros scripts que se ejecutan en diferentes hilos del mismo proceso cambian la configuración de localización con la función setlocale() a nivel de proceso.
Los usuarios de entornos Windows pueden encontrar información útil sobre los valores de localizacion en el sitio web MSDN de Microsoft. Las cadenas válidas para identificar idiomas se pueden consultar en la dirección » http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_language_strings.asp y las cadenas válidas para identificar países/regiones se pueden encontrar en » http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_country_strings.asp. Los sistemas Windows soportan los códigos de 3 letras definidos para los países/regiones por el estándar ISO 3166-Alpha-3, que se puede consultar en » Sitio web de Unicode.
Example #1 Ejemplos de setlocale()
<?php
/* Establecer la localizacion al idioma Holandes */
setlocale(LC_ALL, 'nl_NL');
/* Salida localizada: vrijdag 22 december 1978 */
echo strftime("%A %e %B %Y", mktime(0, 0, 0, 12, 22, 1978));
/* Intentar diferentes nombres para la localizacion al idioma aleman en la version de PHP 4.3.0 */
$localizacion_aleman = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge');
echo "El valor predeterminado del sistema para la localizacion en aleman es '$localizacion_aleman'";
?>
Example #2 Ejemplos de setlocale() en Windows
<?php
/* Establecer la localizacion al idioma Holandes */
setlocale(LC_ALL, 'nld_nld');
/* Salida localizada: vrijdag 22 december 1978 */
echo strftime("%A %d %B %Y", mktime(0, 0, 0, 12, 22, 1978));
/* Intentar diferentes nombres para la localizacion al idioma aleman en la version de PHP 4.3.0 */
$localizacion_aleman = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
echo "El valor predeterminado del sistema para la localizacion en aleman es '$localizacion_aleman'";
?>
setlocale
04-Apr-2008 11:31
21-Jan-2008 02:04
Posting this in the hope it might be useful to others, as I could find very little info anywhere. If you want to use a Welsh locale and have the suitable language support installed, you pass 'cym' (abbreviated form of Cymraeg) to setlocale:
<?php
setlocale(LC_TIME, 'cym');
$welsh= gmstrftime("%A, %B %Y - %H:%M",time());
echo $welsh;
?>
The above certainly applies to Windows systems, but should also apply to Unix if the required support is installed.
Cheers,
Bryn.
27-Dec-2007 11:39
There is a new PECL extension under development called intl (it will be available in PHP5.3). Meanwhile all who rely on the setlocale() and friends should be aware about the limitations of them as covered in this post on the onPHP5.com blog: http://www.onphp5.com/article/22
13-Sep-2007 11:33
In *some* Windows systems, setting LC_TIME only will not work, you must either set LC_ALL or both LC_CTYPE and LC_TIME. BUT if you have already set LC_TIME using setlocale earlier in the script, dates will not be affected! For example:
<?php
setlocale(LC_TIME, 'greek');
setlocale(LC_CTYPE, 'greek');
?>
will not work, while
<?php
setlocale(LC_CTYPE, 'greek');
setlocale(LC_TIME, 'greek');
?>
will do the job.
09-May-2007 02:03
To complement Sven K's tip about debian:
You can also install the package locales-all
That one holds all the locales there are in compiled form.
19-Feb-2007 04:11
For those of you who are unfortunate enough (like me) to work in Windows environment, and try to set the locale to a language _and_ to UTF-8 charset, and were unable to do it, here is a workaround.
For example to output the date in hungarian with UTF-8 charset, this will work:
$dateString = "%B %d., %A";
setlocale(LC_ALL,'hungarian');
$res=strftime($dateString);
echo(iconv('ISO-8859-1', 'UTF-8', $res));
If anybody knows how to set the locale on Windows to the equivalent of "hu_HU.UTF-8" on unix, please do tell me.
20-Nov-2006 06:40
if your server is an ubuntu (debian like)
you need to install the locales you want (default is english and your language) go to aptitude and install -language-pack-*-base it will resolve dependencies and will try to install a suggested package, remove it if you don't care and proceed.
26-Sep-2006 08:15
If you already have all the locales installed and "locale -a" is only showing a few languages, then edit /etc/locale.gen and add a line, e.g., es_MX ISO-8859-1. After you add the line, run the command locale-gen for it to generate the locales based on those settings.
08-Jun-2006 12:08
If your system doesn't show any installed locales by "locale -a", try installing them by "dpkg-reconfigure locales" (on debian).
The example from bruno dot cenou at revues dot org below shows the possibility, but I want to spell it out: you can add charset info to setlocale.
Example:
Into my utf-8-encoded page I want to insert the name of the current month, which happens to be March, in German "März" - with umlaut. If you use
setlocale(LC_TIME, 'de_DE');
echo strftime("%B");
this will return "März", but that html-entity will look like this on a utf-8 page: "M?rz". Not what I want.
But if you use
setlocale(LC_TIME, 'de_DE.UTF8'); // note the charset info !
echo strftime("%B");
this returns "M√§rz", which, on utf-8, looks like it should: "März".
20-Feb-2006 03:31
A little function to test available locales on a sytem :
<?php
function list_system_locales(){
ob_start();
system('locale -a');
$str = ob_get_contents();
ob_end_clean();
return split("\\n", trim($str));
}
$locale = "fr_FR.UTF8";
$locales = list_system_locales();
if(in_array($locale, $locales)){
echo "yes yes yes....";
}else{
echo "no no no.......";
}
?>
20-Feb-2006 01:29
Debian users: Addition to Gabor Deri's note: if setlocale doesn't work in your locale and you're on Debian, and Gabor Deri's note doesn't work, you have to install the locales package.
As root, type: "apt-get install locales" and it will be installed.
30-Nov-2005 08:55
In most Unix/Linux system, you could use:
locale -a
This will list all available locales on the server.
15-Aug-2005 05:42
When i tried to get the current locale (e.g. after i set the lang to german with setlocale(LC_ALL, 'de_DE'); ), the following did not work on my suse linux 9.0-box:
$currentLocale = setlocale(LC_ALL, NULL);
This code did a reset to the server-setting.
$currentLocale = setlocale(LC_ALL, 0); works perfectly for me, but the manual says NULL and 0 are equal in this case, but NULL seems to act like "".
18-Oct-2004 10:42
!!WARNING!!
The "locale" always depend on the server configuration.
i.e.:
When trying to use "pt_BR" on some servers you will ALWAYS get false. Even with other languages.
The locale string need to be supported by the server. Sometimes there are diferents charsets for a language, like "pt_BR.utf-8" and "pt_BR.iso-8859-1", but there is no support for a _standard_ "pt_BR".
This problem occours in Windows platform too. Here you need to call "portuguese" or "spanish" or "german" or...
Maybe the only way to try to get success calling the function setlocale() is:
setlocale(LC_ALL, "pt_BR", "pt_BR.iso-8859-1", "pt_BR.utf-8", "portuguese", ...);
But NEVER trust on that when making functions like date conversions or number formating. The best way to make sure you are doing the right thing, is using the default "en_US" or "en_UK", by not calling the setlocale() function. Or, make sure that your server support the lang you want to use, with some tests.
Remember that: Using the default locale setings is the best way to "talk" with other applications, like dbs or rpc servers, too.
[]s
Pigmeu
13-Aug-2004 01:04
On Novell Netware, the language codes require hyphens, not underscores, and using anything other than LC_ALL doesn't work directly.
So... (from their support list)....
You have to set TIME, NUMERIC etc. info in two steps as given below rather than one. This is due to the limitation of setlocale function of LibC.
<?php
setlocale(LC_ALL, 'es-ES');
$loc = setlocale(LC_TIME, NULL);
echo strftime("%A %e %B %Y", mktime(0, 0, 0, 12, 22, 1978));
// jeuves 22 diciembre 1978
?>
This should work.
or of course, reset LC_ALL...
<?php
setlocale(LC_ALL, 'es-ES');
echo strftime("%A %e %B %Y", mktime(0, 0, 0, 12, 22, 1978));
setlocale(LC_ALL, '');
// jeuves 22 diciembre 1978
?>
02-Mar-2004 11:53
On some systems (at least FreeBSD 4.x) the format for a `locale' is, for example, ro_RO.ISO8859-2. If you use ro_RO instead setlocale will return FALSE. Just browse in /usr/share/locale and see what is the name of the directory holding your `locale' and use that name in your scripts:
<?php
clearstatcache();
$pos = strrpos ($_SERVER["PHP_SELF"], "/");
$fisier = substr ($_SERVER["PHP_SELF"], $pos + 1);
$result = filemtime ($fisier);
$local = setlocale (LC_TIME, 'ro_RO.ISO8859-2');
if ($local == "ro_RO.ISO8859-2") {
$modtime = strftime '%e %B %Y %H:%M', $result);
} else {
$modtime = strftime ('%d.%m.%Y %H:%M', $result);
}
printf ("Ultima actualizare: %s\\n", $modtime);
?>
26-Jan-2004 01:59
Be carefull - setting a locale which uses commas instead of dots in numbers may cause a mysql db not to understand the query:
<?php
setlocale(LC_ALL,"pl");
$price = 1234 / 100; // now the price looks like 12,34
$query = mysql_query("SELECT Id FROM table WHERE price='".$price."'");
?>
Even if there is a price 12.34 - nothing will be found
09-Sep-2002 04:02
be careful with the LC_ALL setting, as it may introduce some unwanted conversions. For example, I used
setlocale (LC_ALL, "Dutch");
to get my weekdays in dutch on the page. From that moment on (as I found out many hours later) my floating point values from MYSQL where interpreted as integers because the Dutch locale wants a comma (,) instead of a point (.) before the decimals. I tried printf, number_format, floatval.... all to no avail. 1.50 was always printed as 1.00 :(
When I set my locale to :
setlocale (LC_TIME, "Dutch");
my weekdays are good now and my floating point values too.
I hope I can save some people the trouble of figuring this out by themselves.
Rob
03-Jul-2002 08:23
I needed to compile and install some extra locales to get this to work on RH7.3. Probably just me not doing a proper installation, but this is what it took to fix it:
localedef -ci no_NO -f ISO_8859-1 no_NO
12-May-2002 11:59
In FreeBSD I had to use no_NO.ISO8859-1 instead of just no_NO..
<?PHP
setlocale (LC_ALL, 'no_NO.ISO8859-1');
echo strftime ("%A %e %B %Y", time());
?>
19-Jun-2001 03:13
Under FreeBSD, locale definitions are stored in the /usr/share/locale/ directory. Danish time formats and weekdays, for instance, are stored in /usr/share/locale/da_DK.ISO_8859-1/LC_TIME.
24-Nov-2000 12:13
On windows:
Control Panel->International Settings
You can set your locale and customize it
And locale-related PHP functions work perfectly
29-Mar-2000 10:56
check /usr/share/locale/ if you want more info about the locale available with your *NIX box
there is also a file called /usr/share/locale/locale.alias with a list of aliases
such as swedish for sv_SE
so on all boxes i have accounts on (rh 6.0 and slack 3.4) you can just use setlocale("LC_ALL","swedish"); or other prefered language in plain english.
However, the weekdays were in all lowercase :(
Note: export LC_ALL=swedish made a lot of programs swedish for me, it's also possible to make them russian or japanese :)
31-Jan-2000 11:57
The Open Group has an excellent document available on the setlocale() library function, most of which applies to the PHP function of the same name.
http://www.opengroup.org/onlinepubs/7908799/xbd/locale.html
WARNING: This document might be a little too complex for people who came from HTML to PHP.
If you migrated from the world of C programming you'll be a locale master after reading this document.
