Как пишется setlocale

title description ms.date api_name api_location api_type topic_type f1_keywords helpviewer_keywords no-loc

setlocale, _wsetlocale

Describes the Microsoft C runtime (CRT) library functions setlocale and _wsetlocale.

05/05/2022

_wsetlocale

setlocale

_o__wsetlocale

_o_setlocale

msvcrt.dll

msvcr80.dll

msvcr90.dll

msvcr100.dll

msvcr100_clr0400.dll

msvcr110.dll

msvcr110_clr0400.dll

msvcr120.dll

msvcr120_clr0400.dll

ucrtbase.dll

api-ms-win-crt-locale-l1-1-0.dll

DLLExport

apiref

_wsetlocale

_tsetlocale

setlocale

wsetlocale function

setlocale function

tsetlocale function

locales, defining

_tsetlocale function

defining locales

_wsetlocale function

setlocale

_wsetlocale

setlocale, _wsetlocale

Sets or retrieves the run-time locale.

Syntax

char *setlocale(
   int category,
   const char *locale
);
wchar_t *_wsetlocale(
   int category,
   const wchar_t *locale
);

Parameters

category
Category affected by locale.

locale
Locale specifier.

Return value

If a valid locale and category are given, the functions return a pointer to the string associated with the specified locale and category.

If the locale or category isn’t valid, the invalid parameter handler is invoked, as described in Parameter validation. If execution is allowed to continue, each function sets errno to EINVAL, and returns NULL.

The call

setlocale( LC_ALL, "en-US" );

sets all categories, returning only the string

You can copy the string returned by setlocale to restore that part of the program’s locale information. Global or thread local storage is used for the string returned by setlocale. Later calls to setlocale overwrite the string, which invalidates string pointers returned by earlier calls.

Remarks

Use the setlocale function to set, change, or query some or all of the current program locale information specified by locale and category. locale refers to the locality (country/region and language) for which you can customize certain aspects of your program. Some locale-dependent categories include the formatting of dates and the display format for monetary values. If you set locale to the default string for a language that has multiple forms supported on your computer, you should check the setlocale return value to see which language is in effect. For example, if you set locale to "chinese" the return value could be either "chinese-simplified" or "chinese-traditional".

_wsetlocale is a wide-character version of setlocale; the locale argument and return value of _wsetlocale are wide-character strings. _wsetlocale and setlocale behave identically otherwise.

By default, this function’s global state is scoped to the application. To change this behavior, see Global state in the CRT.

Generic-text routine mappings

TCHAR.H routine _UNICODE and _MBCS not defined _MBCS defined _UNICODE defined
_tsetlocale setlocale setlocale _wsetlocale

The category argument specifies the parts of a program’s locale information that are affected. The macros used for category and the parts of the program they affect are as follows:

category flag Affects
LC_ALL All categories, as listed below.
LC_COLLATE The strcoll, _stricoll, wcscoll, _wcsicoll, strxfrm, _strncoll, _strnicoll, _wcsncoll, _wcsnicoll, and wcsxfrm functions.
LC_CTYPE The character-handling functions (except isdigit, isxdigit, mbstowcs, and mbtowc, which are unaffected).
LC_MONETARY Monetary-formatting information returned by the localeconv function.
LC_NUMERIC Decimal-point character for the formatted output routines (such as printf), for the data-conversion routines, and for the non-monetary formatting information returned by localeconv. In addition to the decimal-point character, LC_NUMERIC sets the thousands separator and the grouping control string returned by localeconv.
LC_TIME The strftime and wcsftime functions.

This function validates the category parameter. If the category parameter isn’t one of the values given in the previous table, the invalid parameter handler is invoked, as described in Parameter validation. If execution is allowed to continue, the function sets errno to EINVAL and returns NULL.

The locale argument is a pointer to a string that specifies the locale. For information about the format of the locale argument, see Locale names, Languages, and Country/Region strings. If locale points to an empty string, the locale is the implementation-defined native environment. A value of C specifies the minimal ANSI conforming environment for C translation. The C locale assumes that all char data types are 1 byte and that their value is always less than 256.

At program startup, the equivalent of the following statement is executed:

setlocale( LC_ALL, "C" );

The locale argument can take a locale name, a language string, a language string and country/region code, a code page, or a language string, country/region code, and code page. The available locale names, languages, country/region codes, and code pages include all the ones supported by the Windows NLS API. The set of locale names supported by setlocale is described in Locale names, Languages, and Country/Region strings. The set of language and country/region strings supported by setlocale are listed in Language strings and Country/Region strings. We recommend the locale name form for performance and for maintainability of locale strings embedded in code or serialized to storage. The locale name strings are less likely to be changed by an operating system update than the language and country/region name form.

A null pointer that’s passed as the locale argument tells setlocale to query instead of to set the international environment. If the locale argument is a null pointer, the program’s current locale setting isn’t changed. Instead, setlocale returns a pointer to the string that’s associated with the category of the thread’s current locale. If the category argument is LC_ALL, the function returns a string that indicates the current setting of each category, separated by semicolons. For example, the sequence of calls

// Set all categories and return "en-US"
setlocale(LC_ALL, "en-US");
// Set only the LC_MONETARY category and return "fr-FR"
setlocale(LC_MONETARY, "fr-FR");
printf("%sn", setlocale(LC_ALL, NULL));

returns

LC_COLLATE=en-US;LC_CTYPE=en-US;LC_MONETARY=fr-FR;LC_NUMERIC=en-US;LC_TIME=en-US

which is the string that’s associated with the LC_ALL category.

The following examples pertain to the LC_ALL category. Either of the strings «.OCP» and «.ACP» can be used instead of a code page number to specify use of the user-default OEM code page and user-default ANSI code page for that locale name, respectively.

  • setlocale( LC_ALL, "" );

    Sets the locale to the default, which is the user-default ANSI code page obtained from the operating system. The locale name is set to the value returned by GetUserDefaultLocaleName. The code page is set to the value returned by GetACP.

  • setlocale( LC_ALL, ".OCP" );

    Sets the locale to the current OEM code page obtained from the operating system. The locale name is set to the value returned by GetUserDefaultLocaleName. The code page is set to the LOCALE_IDEFAULTCODEPAGE value for the user-default locale name by GetLocaleInfoEx.

  • setlocale( LC_ALL, ".ACP" );

    Sets the locale to the ANSI code page obtained from the operating system. The locale name is set to the value returned by GetUserDefaultLocaleName. The code page is set to the LOCALE_IDEFAULTANSICODEPAGE value for the user-default locale name by GetLocaleInfoEx.

  • setlocale( LC_ALL, "<localename>" );

    Sets the locale to the locale name that’s indicated by <localename>. The code page is set to the LOCALE_IDEFAULTANSICODEPAGE value for the specified locale name by GetLocaleInfoEx.

  • setlocale( LC_ALL, "<language>_<country>" );

    Sets the locale to the language and country/region indicated by <language> and <country>, together with the default code page obtained from the host operating system. The code page is set to the LOCALE_IDEFAULTANSICODEPAGE value for the specified locale name by GetLocaleInfoEx.

  • setlocale( LC_ALL, "<language>_<country>.<code_page>" );

    Sets the locale to the language, country/region, and code page indicated by the <language>, <country>, and <code_page> strings. You can use various combinations of language, country/region, and code page. For example, this call sets the locale to French Canada with code page 1252:

    setlocale( LC_ALL, "French_Canada.1252" );

    This call sets the locale to French Canada with the default ANSI code page:

    setlocale( LC_ALL, "French_Canada.ACP" );

    This call sets the locale to French Canada with the default OEM code page:

    setlocale( LC_ALL, "French_Canada.OCP" );

  • setlocale( LC_ALL, "<language>" );

    Sets the locale to the language that’s indicated by <language>, and uses the default country/region for the specified language and the user-default ANSI code page for that country/region as obtained from the host operating system. For example, the following calls to setlocale are functionally equivalent:

    setlocale( LC_ALL, "en-US" );

    setlocale( LC_ALL, "English" );

    setlocale( LC_ALL, "English_United States.1252" );

    We recommend the first form for performance and maintainability.

  • setlocale( LC_ALL, ".<code_page>" );

    Sets the code page to the value indicated by <code_page>, together with the default country/region and language (as defined by the host operating system) for the specified code page.

The category must be either LC_ALL or LC_CTYPE to effect a change of code page. For example, if the default country/region and language of the host operating system are «United States» and «English«, the following two calls to setlocale are functionally equivalent:

setlocale( LC_ALL, ".1252" );

setlocale( LC_ALL, "English_United States.1252");

For more information, see the setlocale pragma directive in the C/C++ Preprocessor Reference.

The function _configthreadlocale is used to control whether setlocale affects the locale of all threads in a program or only the locale of the calling thread.

UTF-8 support

Starting in Windows 10 version 1803 (10.0.17134.0), the Universal C Runtime supports using a UTF-8 code page. The change means that char strings passed to C runtime functions can expect strings in the UTF-8 encoding. To enable UTF-8 mode, use ".UTF8" as the code page when using setlocale. For example, setlocale(LC_ALL, ".UTF8") will use the current default Windows ANSI code page (ACP) for the locale and UTF-8 for the code page.

The string to specify UTF-8 mode is:

  • case-insensitive
  • the hyphen (-) is optional
  • It must be in the code page part of the locale name, so must have a leading period (.) as in these examples: "en_US.UTF8" or ".utf8"

The following examples show how to specify the UTF-8 string:

".UTF8"
".UTF-8"
".utf8"
".utf-8"
"en_us.utf8"
"ja_JP.Utf-8"

After calling setlocale(LC_ALL, ".UTF8"), you may pass «😊» to mbtowcs and it will be properly translated to a wchar_t string. Previously, there wasn’t a locale setting available to do this translation.

UTF-8 mode is also enabled for functions that have historically translated char strings using the default Windows ANSI code page (ACP). For example, calling _mkdir("😊") while using a UTF-8 code page will correctly produce a directory with that emoji as the folder name, instead of requiring the ACP to be changed to UTF-8 before running your program. Likewise, calling _getcwd() in that folder will return a UTF-8 encoded string. For compatibility, the ACP is still used if the C locale code page isn’t set to UTF-8.

The following aspects of the C Runtime can’t use UTF-8 because they’re set during program startup and must use the default Windows ANSI code page (ACP): __argv, _acmdln, and _pgmptr.

Previous to this support, mbrtoc16, mbrtoc32, c16rtomb, and c32rtomb existed to translate between UTF-8 narrow strings, UTF-16 (same encoding as wchar_t on Windows platforms) and UTF-32. For compatibility reasons, these APIs still only translate to and from UTF-8 and not the code page set via setlocale.

To use this feature on an OS prior to Windows 10, you must use app-local deployment or link statically using version 1803 (10.0.17134.0) of the Windows SDK or later. For Windows 10 operating systems prior to 1803 (10.0.17134.0), only static linking is supported.

Requirements

Routine Required header
setlocale <locale.h>
_wsetlocale <locale.h> or <wchar.h>

For more compatibility information, see Compatibility.

Example

// crt_setlocale.c
//
// This program demonstrates the use of setlocale when
// using two independent threads.
//

#include <locale.h>
#include <process.h>
#include <windows.h>
#include <stdio.h>
#include <time.h>

#define BUFF_SIZE 100

// Retrieve the date in the current
// locale's format.
int get_date(unsigned char* str)
{
    __time64_t ltime;
    struct tm  thetime;

    // Retrieve the current time
    _time64(&ltime);
    _gmtime64_s(&thetime, &ltime);

    // Format the current time structure into a string
    // "%#x" is the long date representation in the
    // current locale
    if (!strftime((char *)str, BUFF_SIZE, "%#x",
                  (const struct tm *)&thetime))
    {
        printf("strftime failed!n");
        return -1;
    }
    return 0;
}

// This thread sets its locale to the argument
// and prints the date.
uintptr_t __stdcall SecondThreadFunc( void* pArguments )
{
    unsigned char str[BUFF_SIZE];
    char * locale = (char *)pArguments;

    // Set the thread locale
    printf("The thread locale is now set to %s.n",
           setlocale(LC_ALL, locale));

    // Retrieve the date string from the helper function
    if (get_date(str) == 0)
    {
        printf("The date in %s locale is: '%s'n", locale, str);
    }

    _endthreadex( 0 );
    return 0;
}

// The main thread sets the locale to English
// and then spawns a second thread (above) and prints the date.
int main()
{
    HANDLE          hThread;
    unsigned        threadID;
    unsigned char   str[BUFF_SIZE];

    // Enable per-thread locale causes all subsequent locale
    // setting changes in this thread to only affect this thread.
    _configthreadlocale(_ENABLE_PER_THREAD_LOCALE);

    // Set the locale of the main thread to US English.
    printf("The thread locale is now set to %s.n",
           setlocale(LC_ALL, "en-US"));

    // Create the second thread with a German locale.
    // Our thread function takes an argument of the locale to use.
    hThread = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc,
                                      "de-DE", 0, &threadID );

    if (get_date(str) == 0)
    {
        // Retrieve the date string from the helper function
        printf("The date in en-US locale is: '%s'nn", str);
    }

    // Wait for the created thread to finish.
    WaitForSingleObject( hThread, INFINITE );

    // Destroy the thread object.
    CloseHandle( hThread );
}
The thread locale is now set to en-US.
The time in en-US locale is: 'Wednesday, May 12, 2004'

The thread locale is now set to de-DE.
The time in de-DE locale is: 'Mittwoch, 12. Mai 2004'

See also

Locale names, Languages, and Country/Region strings
_configthreadlocale
_create_locale, _wcreate_locale
Locale
localeconv
_mbclen, mblen, _mblen_l
strlen, wcslen, _mbslen, _mbslen_l, _mbstrlen, _mbstrlen_l
mbstowcs, _mbstowcs_l
mbtowc, _mbtowc_l
_setmbcp
strcoll functions
strftime, wcsftime, _strftime_l, _wcsftime_l
strxfrm, wcsxfrm, _strxfrm_l, _wcsxfrm_l
wcstombs, _wcstombs_l
wctomb, _wctomb_l

Defined in header <locale.h>

char* setlocale( int category, const char* locale );

The setlocale function installs the specified system locale or its portion as the new C locale. The modifications remain in effect and influences the execution of all locale-sensitive C library functions until the next call to setlocale. If locale is a null pointer, setlocale queries the current C locale without modifying it.

[edit] Parameters

category locale category identifier, one of the LC_xxx macros. May be null.
locale system-specific locale identifier. Can be «» for the user-preferred locale or «C» for the minimal locale

[edit] Return value

pointer to a narrow null-terminated string identifying the C locale after applying the changes, if any, or null pointer on failure.

A copy of the returned string along with the category used in this call to setlocale may be used later in the program to restore the locale back to the state at the end of this call.

[edit] Notes

During program startup, the equivalent of setlocale(LC_ALL, «C»); is executed before any user code is run.

Although the return type is char*, modifying the pointed-to characters is undefined behavior.

Because setlocale modifies global state which affects execution of locale-dependent functions, it is undefined behavior to call it from one thread, while another thread is executing any of the following functions: fprintf, isprint, iswdigit, localeconv, tolower, fscanf, ispunct, iswgraph, mblen, toupper, isalnum, isspace, iswlower, mbstowcs, towlower, isalpha, isupper, iswprint, mbtowc, towupper, isblank, iswalnum, iswpunct, setlocale, wcscoll, iscntrl, iswalpha, iswspace, strcoll, wcstod, isdigit, iswblank, iswupper, strerror, wcstombs, isgraph, iswcntrl, iswxdigit, strtod, wcsxfrm, islower, iswctype, isxdigit.

POSIX also defines a locale named «POSIX», which is always accessible and is exactly equivalent to the default minimal «C» locale.

POSIX also specifies that the returned pointer, not just the contents of the pointed-to string, may be invalidated by subsequent calls to setlocale.

[edit] Example

#include <stdio.h>
#include <locale.h>
#include <time.h>
#include <wchar.h>
 
int main(void)
{
    // the C locale will be UTF-8 enabled English;
    // decimal dot will be German
    // date and time formatting will be Japanese
    setlocale(LC_ALL, "en_US.UTF-8");
    setlocale(LC_NUMERIC, "de_DE.utf8");
    setlocale(LC_TIME, "ja_JP.utf8");
 
    wchar_t str[100];
    time_t t = time(NULL);
    wcsftime(str, 100, L"%A %c", localtime(&t));
    wprintf(L"Number: %.2fnDate: %lsn", 3.14, str);
}

Possible output:

Number: 3,14
Date: 月曜日 2017年09月25日 13時00分15秒

[edit] References

  • C17 standard (ISO/IEC 9899:2018):
  • 7.11.1.1 The setlocale function (p: 163-164)
  • C11 standard (ISO/IEC 9899:2011):
  • 7.11.1.1 The setlocale function (p: 224-225)
  • C99 standard (ISO/IEC 9899:1999):
  • 7.11.1.1 The setlocale function (p: 205-206)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 4.4.1.1 The setlocale function

[edit] See also

(PHP 4, PHP 5, PHP 7, PHP 8)

setlocaleУстанавливает настройки локали

Описание

setlocale(int $category, string $locales, string ...$rest): string|false

Альтернативная сигнатура (не поддерживается с именованными аргументами):

setlocale(int $category, array $locale_array): string|false

Внимание

Информация о локали модифицируется во всем процессе, а не по каждому потоку отдельно.
Если вы используете PHP на многопоточном сервере, вы можете обнаружить неожиданные изменения в настройках локали
во время выполнения скриптов, никогда и не вызывавших setlocale().
Это происходит из-за того, что другие скрипты,
запущенные в параллельных потоках данного процесса, в то же самое время поменяли
настройки локали для всего процесса с помощью setlocale().
В Windows информация о локали поддерживается для каждого потока, начиная с PHP 7.0.5.

Список параметров

category

Параметр category — это именованная константа,
определяющая категорию функций, на которые будет влиять установка локали:


  • LC_ALL — все нижеперечисленное

  • LC_COLLATE — функции сравнения строк, смотрите
    strcoll()

  • LC_CTYPE — функции преобразования и классификации строк, например
    ctype_alpha()

  • LC_MONETARY — для функции localeconv()

  • LC_NUMERIC — задаёт символ десятичного разделения (смотрите также
    localeconv())

  • LC_TIME — форматирование даты/времени функцией
    strftime()

  • LC_MESSAGES — для системных сообщений (доступна, если PHP был скомпилирован с поддержкой
    libintl)
locales

Если в качестве locales передана пустая строка
"" или null, имена локалей будут взяты из одноимённых
переменных окружения или переменной с именем «LANG».

Если в качестве locales передан
"0", локаль изменена не будет, а будет возвращено
текущее значение.

Если в качестве locales передан массив, или
после этого аргумента следуют дополнительные аргументы, функция будет
использовать элементы массива или аргументы по порядку в качестве
имён локали до тех пор, пока установка локали не будет успешной.
Это удобно, если одна и та же локаль имеет разное имя в различных
системах, или для создания запасного варианта при отсутствии какой-либо локали в системе.

rest

Необязательные аргументы в виде строк или массивов для установки настроек локали
до первой успешной попытки.

locale_array

Каждый элемент массива пытается установить новую локаль до первой успешной попытки.
Это полезно, если локаль известна под разными именами в разных системах или для обеспечения запасного варианта
для возможно недоступного языкового стандарта.

Замечание:

На Windows setlocale(LC_ALL, ») устанавливает имена локалей из системных
региональных/языковых настроек (доступных через Панель Управления).

Возвращаемые значения

Возвращает имя вновь установленной локали или false, если
система не поддерживает установку локали, указанная локаль не
существует или передано недопустимое имя категории.

Недопустимое имя категории также вызывает предупреждение. Имена
локалей и категорий описаны в » RFC 1766
и » ISO 639.
Разные системы имеют различные схемы именования локалей.

Замечание:

Возвращаемое функцией setlocale() значение
зависит от системы, на которой запущен PHP. Она возвращает точно то же
значение, что и системная функция setlocale.

Примеры

Пример #1 Примеры использования setlocale()


<?php
/* Установка голландской локали */
setlocale(LC_ALL, 'nl_NL');/* выводит: vrijdag 22 december 1978 */
echo strftime("%A %e %B %Y", mktime(0, 0, 0, 12, 22, 1978));/* попытка использовать различные локали для немецкого языка */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge');
echo
"На этой системе немецкая локаль имеет имя '$loc_de'";
?>

Пример #2 Примеры использования setlocale() в Windows


<?php
/* Установка голландской локали */
setlocale(LC_ALL, 'nld_nld');/* выводит: vrijdag 22 december 1978 */
echo strftime("%A %d %B %Y", mktime(0, 0, 0, 12, 22, 1978));/* попытка использовать различные локали для немецкого языка */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
echo
"Предпочитаемая немецкая локаль на этой системе: '$loc_de'";
?>

Примечания

r dot nospam dot velseboer at quicknet dot nospam dot nl

20 years ago


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


russ at eatmymonkeydust dot com

11 years ago


If you are looking for a getlocale() function simply pass 0 (zero) as the second parameter to setlocale().

Beware though if you use the category LC_ALL and some of the locales differ as a string containing all the locales is returned:

<?php
echo setlocale(LC_ALL, 0);// LC_CTYPE=en_US.UTF-8;LC_NUMERIC=C;LC_TIME=C;LC_COLLATE=C;LC_MONETARY=C;LC_MESSAGES=C;LC_PAPER=C;LC_NAME=C;
// LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=C;LC_IDENTIFICATION=C
echo setlocale(LC_CTYPE, 0);// en_US.UTF-8setlocale(LC_ALL, "en_US.UTF-8");
echo
setlocale(LC_ALL, 0);// en_US.UTF-8?>

If you are looking to store and reset the locales you could do something like this:

<?php

$originalLocales

= explode(";", setlocale(LC_ALL, 0));
setlocale(LC_ALL, "nb_NO.utf8");// Do somethingforeach ($originalLocales as $localeSetting) {
  if (
strpos($localeSetting, "=") !== false) {
    list (
$category, $locale) = explode("=", $localeSetting);
  }
  else {
   
$category = LC_ALL;
   
$locale   = $localeSetting;
  }
 
setlocale($category, $locale);
}
?>

The above works here (Ubuntu Linux) but as the setlocale() function is just wrapping the equivalent system calls, your mileage may vary on the result.


epistomai at gmail dot com

3 years ago


setlocale(LC_MONETARY, 'en_US') doesn't work anymore (at least in PHP Version 7.3.8).

I've used 'en_US.UTF-8' instead


Shashakhmetov Talgat

7 years ago


//Fix encoding for russian locale on windows
$locale = setlocale(LC_ALL, 'ru_RU.CP1251', 'rus_RUS.CP1251', 'Russian_Russia.1251');

function strftime_fix($format, $locale, $timestamp = time()){
    // Fix %e for windows
    if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
        $format = preg_replace('#(?<!%)((?:%%)*)%e#', '1%#d', $format);
    }
    // convert
    $date_str = strftime($format, $timestamp);
    if (stripos($locale, "1251") !== false) {
      return iconv("windows-1251","utf-8", $date_str);
    } elseif (stripos($locale, "1252") !== false) {
      return iconv("windows-1252","utf-8", $date_str);
    } else {
      return $date_str;
    }
}


brice/axice/be

14 years ago


Pay attention to the syntax.

- UTF8 without dash ('-')

- locale.codeset and not locale-codeset.

Stupid newbie error but worth knowing them when starting with gettext.

<?php

$codeset
= "UTF8"// warning ! not UTF-8 with dash '-'

       
// for windows compatibility (e.g. xampp) : theses 3 lines are useless for linux systems

putenv('LANG='.$lang.'.'.$codeset);

putenv('LANGUAGE='.$lang.'.'.$codeset);

bind_textdomain_codeset('mydomain', $codeset);
// set locale

bindtextdomain('mydomain', ABSPATH.'/locale/');

setlocale(LC_ALL, $lang.'.'.$codeset);

textdomain('mydomain');

?>



where directory structure of locale is (for example) :

locale/fr_FR/LC_MESSAGES/mydomain.mo

locale/en_US/LC_MESSAGES/mydomain.mo

and ABSPATH is the absolute path to the locale dir

further note, under linux systems, it seems to be necessary to create the locale at os level using 'locale-gen'.


Kari Sderholm aka Haprog

13 years ago


It took me a while to figure out how to get a Finnish locale correctly set on Ubuntu Server with Apache2 and PHP5.

At first the output for "locale -a" was this:
C
en_US.utf8
POSIX

I had to install a finnish language pack with
"sudo apt-get install language-pack-fi-base"

Now the output for "locale -a" is:
C
en_US.utf8
fi_FI.utf8
POSIX

The last thing you need to do after installing the correct language pack is restart Apache with "sudo apache2ctl restart". The locale "fi_FI.utf8" can then be used in PHP5 after restarting Apache.

For setting Finnish timezone and locale in PHP use:
<?php
date_default_timezone_set
('Europe/Helsinki');
setlocale(LC_ALL, array('fi_FI.UTF-8','fi_FI@euro','fi_FI','finnish'));
?>


pigmeu at pigmeu dot net

18 years ago


!!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


data dot ocean dot italia at gmail dot com

10 years ago


Instead, using php with IIS, I had to use this line for Italian language...

<?php setlocale(LC_ALL, 'Italian_Italy.1250'); ?>


jose dot nobile at gmail dot com

7 years ago


For Windows users complaining about setlocale.

The locale argument to the setlocale function takes the following form:
setlocale( LC_ALL, "<language>_<country>.<code_page>" );

in short, if you  want use for example: es_CO.UTF-8 it must be in Windows: Spanish_Colombia.1252

The code page 1252 is ISO-8859-1 (windows-1252    ANSI Latin 1; Western European (Windows)

Windows use different languages code from Unix, for example, es_CO becomes es-CO or Spanish_Colombia, also it doesn't support UTF-8 charset as is shown in their website: https://msdn.microsoft.com/en-us/library/x99tb11d(v=vs.140).aspx

"The set of available locale names, languages, country/region codes, and code pages includes all those supported by the Windows NLS API except code pages that require more than two bytes per character, such as UTF-7 and UTF-8. If you provide a code page value of UTF-7 or UTF-8, setlocale will fail, returning NULL."

Please check the updated website of language and code pages:

https://msdn.microsoft.com/en-us/library/39cwe7zf(v=vs.140).aspx
and
https://msdn.microsoft.com/en-us//goglobal/bb895996

Here a copy paste in case the link is removed:

Afrikaans
Albanian
Arabic_Saudi_Arabia
Arabic_Iraq
Arabic_Egypt
Arabic_Libya
Arabic_Algeria
Arabic_Morocco
Arabic_Tunisia
Arabic_Oman
Arabic_Yemen
Arabic_Syria
Arabic_Jordan
Arabic_Lebanon
Arabic_Kuwait
Arabic_UAE
Arabic_Bahrain
Arabic_Qatar
Armenian
Azeri_Latin
Azeri_Cyrillic
Basque
Belarusian
Bengali_India
Bosnian_Latin
Bulgarian
Catalan
Chinese_Taiwan
Chinese_PRC
Chinese_Hong_Kong
Chinese_Singapore
Chinese_Macau
Croatian
Croatian_Bosnia_Herzegovina
Czech
Danish
Divehi
Dutch_Standard
Dutch_Belgian
English_United_States
English_United_Kingdom
English_Australian
English_Canadian
English_New_Zealand
English_Ireland
English_South_Africa
English_Jamaica
English_Caribbean
English_Belize
English_Trinidad
English_Zimbabwe
English_Philippines
Estonian
Faeroese
Farsi
Finnish
French_Standard
French_Belgian
French_Canadian
French_Swiss
French_Luxembourg
French_Monaco
Georgian
Galician
German_Standard
German_Swiss
German_Austrian
German_Luxembourg
German_Liechtenstein
Greek
Gujarati
Hebrew
Hindi
Hungarian
Icelandic
Indonesian
Italian_Standard
Italian_Swiss
Japanese
Kannada
Kazakh
Konkani
Korean
Kyrgyz
Latvian
Lithuanian
Macedonian
Malay_Malaysia
Malay_Brunei_Darussalam
Malayalam
Maltese
Maori
Marathi
Mongolian
Norwegian_Bokmal
Norwegian_Nynorsk
Polish
Portuguese_Brazilian
Portuguese_Standard
Punjabi
Quechua_Bolivia
Quechua_Ecuador
Quechua_Peru
Romanian
Russian
Sami_Inari
Sami_Lule_Norway
Sami_Lule_Sweden
Sami_Northern_Finland
Sami_Northern_Norway
Sami_Northern_Sweden
Sami_Skolt
Sami_Southern_Norway
Sami_Southern_Sweden
Sanskrit
Serbian_Latin
Serbian_Latin_Bosnia_Herzegovina
Serbian_Cyrillic
Serbian_Cyrillic_Bosnia_Herzegovina
Slovak
Slovenian
Spanish_Traditional_Sort
Spanish_Mexican
Spanish_Modern_Sort
Spanish_Guatemala
Spanish_Costa_Rica
Spanish_Panama
Spanish_Dominican_Republic
Spanish_Venezuela
Spanish_Colombia
Spanish_Peru
Spanish_Argentina
Spanish_Ecuador
Spanish_Chile
Spanish_Uruguay
Spanish_Paraguay
Spanish_Bolivia
Spanish_El_Salvador
Spanish_Honduras
Spanish_Nicaragua
Spanish_Puerto_Rico
Swahili
Swedish
Swedish_Finland
Syriac
Tamil
Tatar
Telugu
Thai
Tswana
Ukrainian
Turkish
Ukrainian
Urdu
Uzbek_Latin
Uzbek_Cyrillic
Vietnamese
Welsh
Xhosa
Zulu

The code pages identifiers:

https://msdn.microsoft.com/en-us/library/windows/desktop/dd317756(v=vs.85).aspx


Periklis

15 years ago


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.

Sven K

16 years ago


If your system doesn't show any installed locales by "locale -a", try installing them by "dpkg-reconfigure locales" (on debian).

Leigh Morresi

14 years ago


Setting locale that is not supported by your system will result in some string operations returning a question mark "?" in your strings where it needs to perform transliteration.

1) Always check the return of setlocale() to ensure it has set to something supported

2) on Linux you can use the "locale -a" command to find a list of supported locales


RobQuist

9 years ago


In addition to russ, about getting / backing up the locale:
I'm using this in unit-tests. I wanted to test something based on locale, and reset the locale after the tests were done.

Yet there were some errors;
* setlocale doesn't like strings anymore. You need to use constants.
* Some contants don't exist anymore.

Here's an updated piece of code:

<?php
$originalLocales
= explode(";", setlocale(LC_ALL, 0));
setlocale(LC_ALL, 'nl_NL.UTF-8');//Do something here

//Recover to the default setting

$skipConstants = array( //these will be returned by setlocale(LC_ALL, 0), but don't exist anymore.
           
'LC_PAPER',
           
'LC_NAME',
           
'LC_ADDRESS',
           
'LC_TELEPHONE',
           
'LC_MEASUREMENT',
           
'LC_IDENTIFICATION'
       
);

        foreach (

$originalLocales as $localeSetting) {
            if (
strpos($localeSetting, "=") !== false) {
                list (
$category, $locale) = explode("=", $localeSetting);
            } else {
               
$category = LC_ALL;
               
$locale   = $localeSetting;
            }

            if (!

in_array($category, $skipConstants)) {
               
setlocale(constant($category), $locale); //Using strings is deprecated.
           
}
        }
?>


Anonymous

16 years ago


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&auml;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".


bryn AT lunarvis DOT com

15 years ago


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.


tomas dot hampl at gmail dot com

11 years ago


On Linux, setlocale() depends on the installed locales. To see which locales are available to PHP, run this from the terminal:

"locale -a"

Provided list are all locales that are available on your server for PHP to use. To add a new one, run

locale-gen <locale name> (this may need sudo / root permissions), for example to add a Czech locale, run something like this:

"sudo locale-gen cs_CZ.utf8"

Then you can use this locale declaration:

setlocale(LC_ALL, 'cs_CZ.utf8');


szepeshazi at gmail dot com

16 years ago


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.


divinity76 at gmail dot com

8 months ago


if someone is looking for a getlocale(),

<?php
if(!function_exists("getlocale")){
    function
getlocale(int $category)/*:string|false*/{
        return
setlocale($category, 0);
    }
}
?>


birkholz at web dot de

17 years ago


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 "".


lingureanumanuel at yahoo dot com

1 year ago


for windows

setlocale(LC_ALL, 'Greenlandic_Greenland.1252');
will return false

to make it work use
setlocale(LC_ALL, 'Kalaallisut_Greenland.1252');


mk at totu dot com

19 years ago


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

Un_passant

14 years ago


For debian/ubuntu, don't forget the charset UFT8.

// Works on Ubuntu 8.04 Server
setlocale(LC_TIME, 'fr_FR.UTF8', 'fr.UTF8', 'fr_FR.UTF-8', 'fr.UTF-8');


tim dot peters at live dot com

3 years ago


Maybe obvious, but I would expect that setlocale constantes (LC_*) would be bitwise, but they're not.

In example, doing this:

<?php
    setlocale
(LC_TIME + LC_COLLATE, 'nl');

    echo

setlocale(LC_ALL, 0);
?>
would cause the following result:

LC_CTYPE=C;LC_NUMERIC=C;LC_TIME=C;LC_COLLATE=C;LC_MONETARY=C;LC_MESSAGES=nl;LC_PAPER=C;
LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=C;LC_IDENTIFICATION=C

Note that LC_MESSAGES has changed, instead of LC_TIME and LC_COLLATE. (Because LC_TIME + LC_COLLATE = LC_MESSAGES).

Instead you would need to specify them individually, if you don't wish to use LC_ALL:

<?php
    setlocale
(LC_TIME, 'nl');
   
setlocale(LC_COLLATE, 'nl');

    echo

setlocale(LC_ALL, 0);
?> LC_CTYPE=C;LC_NUMERIC=C;LC_TIME=nl;LC_COLLATE=nl;LC_MONETARY=C;LC_MESSAGES=C;LC_PAPER=C;
LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=C;LC_IDENTIFICATION=C


stepdate at gmail dot com

5 years ago


If you have Locales installed and things won't work check the spelling: for German all the comments suggested "setlocale(LC_TIME, "de_DE.utf8")", but it has to be "setlocale(LC_TIME, "de_DE.UTF-8")"-> UTF-8 instead of utf8.

internationalist

7 years ago


My script runs a loop that changes the locale (multilingual application). I've noticed that on some random occasion the locale still hasn't changed despite the setlocale() function being executed a step earlier. I had to add wait time for this condition. Interestingly enough, this was the case only with the 'nl_NL.UTF8' locale.

<?php
//some code
$this->counter = 0;
// some code
$this->locale = 'nl_NL.UTF8';
setlocale(LC_ALL, $this->locale);
   
$this->counter++;
    if (
$this->locale !== setlocale(LC_CTYPE, 0)) { // Locale not changed yet.
     
if ($this->counter > 10) {
        return;
      }
     
sleep(1);
    }
// some code
?>


aaaaa976 at gmail dot com

8 years ago


In Windows some times setlocale don't work, it return a empty array, buts the locale is set. I found that apache start before windows "load" locales, you must restart apache to solve this.

phcorp

11 years ago


To find the locale of a Unix system:
<?php system('locale -a') ?>

leif at neland dot dk

12 years ago


Regarding dash'es in locale, it appears they should be omitted entirely.

In /etc/locale.gen I have

da_DK.ISO-8859-15 ISO-8859-15

but locale -a gives

da_DK.iso885915

which is the format setlocale()  wants.

(Debian)


garygendron at yahoo dot com

12 years ago


For a php Mysql query, you could also use, for french canadian, in this example :

$query = 'SET lc_time_names = "fr_CA"';
$result = mysql_query($query) or die("Query failed");

$query = 'SELECT @@lc_time_names';
$result = mysql_query($query) or die("Query failed");

$query = 'SELECT id, created, YEAR(created) as year, MONTH(created) as month,' .
' CONCAT_WS(" ", MONTHNAME(created), YEAR(created)) as archive' .           
' FROM #__TABLE as e' .
' GROUP BY archive' .
' ORDER BY id DESC';

Your data will be displayed in any locale setting you want. You may even $_GET[lc_time_name] from your multilanguage website.


michal dot kocarek at brainbox dot cz

14 years ago


Note about using UTF-8 locale charset on Windows systems:

According to MSDN, Windows setlocale()'s implementation does not support UTF-8 encoding.

Citation from "MSDN setlocale, _wsetlocale" page (http://msdn.microsoft.com/en-us/library/x99tb11d.aspx):

The set of available languages, country/region codes, and code pages includes all those supported by the Win32 NLS API except code pages that require more than two bytes per character, such as UTF-7 and UTF-8. If you provide a code page like UTF-7 or UTF-8, setlocale will fail, returning NULL.

So basically, code like

<?php setlocale(LC_ALL, 'Czech_Czech Republic.65001'); // 65001 is UTF-8 codepage ?>

does not work on Windows at all.

(written in time of PHP 5.2.4)


mvanbaak

15 years ago


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.


ostapk

15 years ago


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

flavioacvalverde at gmail dot com

11 years ago


For Portugal I had to use

<?php setlocale(LC_ALL, 'Portuguese_Portugal.1252'); ?>



using php with IIS on Windows server.


totn C Functions


In the C Programming Language, the setlocale function allows you to set the program’s locale information.

Syntax

The syntax for the setlocale function in the C Language is:

char *setlocale(int category, const char *locale);

Parameters or Arguments

category
The program’s locale to change. It can either be one category or all categories.
locale
A pointer to a string which contains the new locale.

Note

  • If category is LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, or LC_TIME macro, the setlocale function will only update one category.
  • If category is LC_ALL, the setlocale function will update all categories.

Returns

If locale is a null pointer, the setlocale function returns a pointer to the string associated with category for the current locale. If the locale is not a null pointer, the setlocale function returns a pointer to the string associated with category for the new locale.

If the setlocale function fails, a null pointer will be returned.

Required Header

In the C Language, the required header for the setlocale function is:

#include <locale.h>

Applies To

In the C Language, the setlocale function can be used in the following versions:

  • ANSI/ISO 9899-1990

setlocale Example

/* Example using setlocale by TechOnTheNet.com */

#include <stdio.h>
#include <locale.h>

int main(int argc, const char * argv[])
{
    /* Define a temporary variable */
    struct lconv *loc;

    /* Set the locale to the POSIX C environment */
    setlocale (LC_ALL, "C");

    /* Retrieve a pointer to the current locale */
    loc = localeconv();

    /* Display some of the locale settings */
    printf("Thousands Separator: %sn", loc->thousands_sep);
    printf("Currency Symbol: %sn", loc->currency_symbol);

    /* Set the locale to the environment default */
    setlocale (LC_ALL, "");

    /* Retrieve a pointer to the current locale */
    loc = localeconv();

    /* Display some of the locale settings */
    printf("Thousands Separator: %sn", loc->thousands_sep);
    printf("Currency Symbol: %sn", loc->currency_symbol);

    return 0;
}

When compiled and run on a machine in North America, this application will output:

Thousands Separator: 
Currency Symbol: 
Thousands Separator: ,
Currency Symbol: $

Similar Functions

Other C functions that are similar to the setlocale function:

  • localeconv function <locale.h>

Перейти к содержимому

Функция setlocale позволяет настраивать локальные, например, российские, параметры в программе. С помощью этой функции, например, можно выбрать русский язык в консоли. 

Чтобы воспользоваться данной функцией, необходимо подключить заголовочный файл:

В программе данная функция  выглядит следующим образом:

Где перед запятой прописывается параметр константы. Наиболее популярная константа LC_ALL. Она влияет на всё, но есть и некоторые другие константы.

После запятой, в кавычках, прописывается имя локали. Например, russian. Рассмотрим, как выбрать русский язык в консоли в ОС Windows:

#include <windows.h> // подключаем все используемые функции, setlocale (из locale.h) подключится автоматически

void main()

{

  SetConsoleCP(1251);

  SetConsoleOutputCP(1251);

  setlocale(LC_ALL,«russian»);

}

В данном примере, функции SetConsoleCP и SetConsoleOutputCP устанавливают кириллицу для программы. Кириллица имеет, например, такие кодировки: cp866 — старая ДОСовская и cp1251 – новая, от Windows.

Третья функция — setlocale(LC_ALL, “russian”)  говорит о том, что применяется настройка для всей программы (т.к. используется LC_ALL) в виде установки русского языка (т.к. используется “russian”).

Понравилась статья? Поделить с друзьями:
  • Как пишется sell out
  • Как пишется self made
  • Как пишется security
  • Как пишется season
  • Как пишется scratch