laban

setlocale() will not work

4 posts in this topic

I have a webpage that I (think have) worked well with translation of dates based on a setlocale() code in a _init.php file until now.

The page is in Norwegian (default) and English (english). But the date shown front end is now only in English. I have a multi-language textfield (locale) where I input nb_NO and en_US, and then I use the follow code in _init.php:

$homepage = $pages->get('/');

// For change of language, set default language
switch($user->language->name) {
    case 'default':
        setlocale (LC_ALL, $homepage->locale);
        break;
}

To check what is output, I used this:

echo setlocale(LC_ALL, 0);

And it only outputs C both on the Norwegian and English page. (It should output nb_NO and en_US).

I have the same setup on another page, at least I think so, but something must be different.

I also tried changing the locale, and editing LanguageSupport.module, removing the setlocale() code from above, with no luck. I check both in development (MAMP) and on my production server.

I use ProcessWire 3.0.59 (live) and 3.0.60 (development).

There could be other code I have that messes this up. But I hope this could shine som light. My question is: What decides the locale and how could I fix the «C»?

Share this post


Link to post
Share on other sites

I'm not sure this is the issue, because you're experiencing it locally as well as in production, but setlocale() can only work if the locale is actually installed on the running machine. If not it will silently refuse to change. 

Share this post


Link to post
Share on other sites

Not a definitive solution, but you can use strftime for locale-specific dates. From its documentation

Quote

Format the time and/or date according to locale settings. Month and weekday names and other language-dependent strings respect the current locale set with setlocale().

then you'd do something like this.

<?php
function formatDate($format, $timestamp)
{
  	// set first possible locale from the list
    setlocale(LC_TIME, ['no_NO', 'no_NN', 'no_NB']);
    return strftime($format, $timestamp);
}

One thing to note is that you need to use strftime specific date format.

1 person likes this

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.