Pretty time formatting with setlocale and strftime

November 15th, 2010 by Alex Leave a reply »

You’ve probably heard of setlocale and it’s ability to set country- or language-specific settings. Now if you are curious why doesn’t it work, here’s a simple template to make sure you don’t mess it up..

As we know, setlocale accepts two arguments: a category and a locale (or an array or list of locales).
The category is one of these:

  • LC_ALL

Each of these are used for particular functions. For ex., LC_CTYPE is used for character manipulations, and LC_TIME is used for strftime or gmstrftime or other similar ones. So, what we need is to call something like this:

setlocale(LC_TIME, 'en_US.UTF-8');

This will set language to English, country to United States, and encoding to UTF-8. So, you may see that you can find out the locale using this template:

$locale = $language.'_'.$country.'.'.$encoding;
setlocale(LC_TIME, $locale);

Now, all you need to do is find a locale for your language (whether it’s Vietnamese or Turkish or Russian) in the ISO639-1 table of countries and find a 2-symbol language code there. Then, look up the 2-symbol country code in the ISO 3166-1-alpha-2 table.

So, for Russian language you may have something like:

setlocale(LC_TIME, 'ru_RU.UTF-8');

Some basic encodings list for you to make sure you spell it correctly (i.e. UTF8 won’t work, only UTF-8):

  • ISO8859-1 … ISO8859-15
  • KOI8-R
  • KOI8-U
  • CP866
  • CP1251
  • eucJP
  • eucKR
  • eucCN
  • Big5
  • GBK
  • UTF-8

Now, you can output dates using built-in strftime in native language.. But also you should understand that systems may vary greatly, so just experiment with locale string if it didn’t work.

So, now you can use strftime and not worry about server language weekday names

This page can be found by searching for:

wordpress setlocalesetlocale htaccesshtaccess setlocalehtaccess set locale

Comments are closed.