Urs
Urs

Reputation: 5122

Set multiple locales on one page

On a webpage that contains items in various languages, it would be desired to display different dates in different languages:

jeudi, 15 octobre next to Donnerstag, 15. Oktober - on the same page.

Ist that possible?

Upvotes: 1

Views: 1311

Answers (2)

lxg
lxg

Reputation: 13107

When you switch the locale with setlocale, the set locale is being used for everything after that.

So you could create a custom function which will switch the locale just for the desired output and then switch back. The following should work:

function locDate($format, $locale, $time = null)
{
    $oldlocale = setlocale(LC_ALL, "0"); // get the current locale
    setlocale(LC_ALL, $locale);

    $date = date($format, $time);

    setlocale(LC_ALL, $oldlocale);
    return $date;
}

Using this for localized dates is just an example. This approach works with everything that gives different output based on the current locale.

This also works if you're using gettext for string translation. You can temporarily switch the locale to output certain chunks of text in a different language (assuming that a translation exists in your catalog and the catalog is loaded).

Upvotes: 5

geofflee
geofflee

Reputation: 3781

lxg's answer above is mostly correct, but it has a couple problems:

  1. You must use strftime() instead of date(). This is because PHP's date() function ignores setlocale(). Note that strftime() uses a slightly different format.
  2. The call to setlocale() is system dependent. On my system, setlocale(LC_ALL, "0") returns the string:

    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

    You definitely don't want to pass that entire string back into setlocale(). The solution is to use LC_TIME instead of LC_ALL.

Corrected function looks like this:

function locDate($format, $locale, $time = null)
{
    $oldlocale = setlocale(LC_TIME, "0"); // get the current locale
    setlocale(LC_TIME, $locale);

    $date = strftime($format, $time);

    setlocale(LC_TIME, $oldlocale);
    return $date;
}

Upvotes: 7

Related Questions