Search code examples
phpdatetimemultilingual

local language without strftime (deprecated) but with date


So, i used this code before strftime() became deprecated:

setlocale(LC_TIME, IT);
echo "<p>" . strftime("%A %e %h %Y", strtotime($value)) . "</p>";

strftime() output

And now, using date() with the same code the output do not change language.

setlocale(LC_TIME, 'it_IT.utf8');
echo "<p>" . date("l d M Y", strtotime($value)) . "</p>";

date() output

**ignore variable $value

I don't see differences between setlocale(LC_TIME, 'IT') and setlocale(LC_TIME, 'it_IT.utf8') on date()... but strftime() works only with setlocale(LC_TIME, 'IT') and not the second one

Any ideas?


Solution

  • date() function use format accepted by DateTimeInterface::format() method.

    The method DateTimeInterface::format() does not use locales. All output is in English.
    So, this means that date() function also not use locales either.

    Testing:

    setlocale(LC_ALL, 'IT.utf8');
    echo date('l', time()).'<br>';// display Friday
    
    setlocale(LC_ALL, 'fr');
    echo date('l', time()).'<br>';// display Friday
    
    setlocale(LC_ALL, 'th');
    echo date('l', time()).'<br>';// display Friday
    

    All locales display the same: Friday.

    strftime() is deprecated.

    What is the replacement for display date/time with locales (and maybe including time zone)?
    The IntlDateFormatter is the best option.

    From your previous code:

    setlocale(LC_TIME, 'IT.utf8');
    echo "<p>" . strftime("%A %e %h %Y", time()) . "</p>";// display venerdì 15 apr 2022
    

    You can now use:

    $fmt = new IntlDateFormatter('IT',
        IntlDateFormatter::FULL, 
        IntlDateFormatter::FULL
    );
    $fmt->setPattern('EEEE d LLL yyyy');
    echo $fmt->format(time());// display venerdì 15 apr 2022
    

    The format will be use setPattern() method and possible patterns are documented at https://unicode-org.github.io/icu/userguide/format_parse/datetime/.