25

I have a script that needs to display date data to an international audience - e.g.

"submitted Tue 25 Aug 09"

Is there an easier/cleaner way to get this converted to the French(etc) equivalent "Mar 25 Aoû 09" than:

Setting a constant LANG and a $LANGUAGES array of include files & :

if(LANG != 'EN')
{
include $LANGUAGES['LANG'];
}

& then the included file maps the days & months & replaces for the appropriate locale?

Dharman
  • 30,962
  • 25
  • 85
  • 135
David Miller
  • 2,189
  • 2
  • 15
  • 17

3 Answers3

54

I think you can't get away from doing so without setting LOCALE:

<?php
setlocale(LC_ALL, 'fr_FR');

echo strftime("%A %e %B %Y");
?> 

Some details on strftime: http://us2.php.net/manual/en/function.strftime.php

Jakub
  • 20,418
  • 8
  • 65
  • 92
  • 5
    This is the correct/PHP way of handling locale in date strings. `strftime()` is preferred over `date()` when you need to account for locale. – dcousineau Aug 25 '09 at 13:45
  • The above code won't work on Windows as the `%e` parameter doesn't work on Windows as stated in the docs. You have to make an additional check, example is shown under **Example #3 Cross platform compatible example using the %e modifier** of the [strftime() docs](http://us2.php.net/manual/en/function.strftime.php) – Stan Sep 28 '15 at 20:56
  • 4
    Does not work for me (using Linux). It's still in English –  Mar 18 '17 at 09:07
  • 1
    This is an old post, but I might add that for you to be able to set another locale in PHP, or at least to make it change anything, you will need to have that locale installed on the actual server (at least on Linux). – M. Eriksson Mar 02 '18 at 06:38
  • 1
    This used to be a great answer, but `strftime` has been deprecated as of PHP 8.1 according to https://www.php.net/strftime – MrSnoozles Aug 05 '22 at 12:57
  • 1
    See my updated answer here on how to do this in 2022: https://stackoverflow.com/a/73250691/1671294 – MrSnoozles Aug 05 '22 at 13:40
6

According to the date function's manual page, you should use setlocale. Methods such as strftime will then use the locale specified. date, however, will not for some reason.

Robin
  • 9,415
  • 3
  • 34
  • 45
Samir Talwar
  • 14,220
  • 3
  • 41
  • 65
4

I think that the best way to do it with strftime and setlocale functions. But it will not work if your server has no needed locale installed (in current questions it is fr_FR).

Code bellow throw an exception if locale change will be unsuccessful

<?php

$result = setlocale(LC_ALL, 'fr_FR');

if($result === false){
    throw new \RuntimeException(
        '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 Aoû 09 - month shortname, day of month, day shortname, year last two digits
echo strftime("%b $dayOfMonth %a %y"); 
Artur Babyuk
  • 288
  • 2
  • 8