PHP setlocale and strftime Not Working

Last updated on

I was recently having problems displaying the day and month name in my local language after a server move. This was due to a missing locale.

If you don’t have shell access to your server, you may need to contact your web host for assistance.

Firstly, check which locales are currently installed on the server.

locale -a
en_US.utf8

Above we can see only en_US.utf8 is installed. If your required locale is missing, you may need to install it using dpkg-reconfigure locales.

sudo pkg-reconfigure locales

Select your required local and and press OK.

Now run locale -a again to see if you locale appears.

Make sure to restart your web server or PHP when adding a new locale.

You can use the following PHP script to test if a local is available to PHP or not.

test.php
<?php
$result = setlocale(LC_ALL, 'en_US.utf-8');

if($result === false){
 die('Got error changing locale, check if locale is installed on the system');
}

$dayOfMonth = '%e';
//if it is Windows we will use %#d as %e is not supported
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
 $dayOfMonth = '%#d';
}

//Mar 25 Aug 09 - month shortname, day of month, day shortname, year last two digits
echo strftime("%b $dayOfMonth %a %y");
?>

Let me know in the comments if this helped. Follow me on Twitter, Facebook and YouTube.

p.s. I increased my AdSense revenue by 68% using AI 🤖. Read my Ezoic review to find out how.

1 Star2 Stars3 Stars4 Stars5 Stars 5.00 (1 votes)

Leave a Reply

Your email address will not be published. Required fields are marked *

We use Markdown to style comments, like on Github and Reddit.
To do a line break, type two spaces after the sentence.
You can add inline code by wrapping it in backticks: `code here`

    To do an entire block of code  
    type four spaces before the line
    and it will appear in a block like this.
    <-- four empty spaces