Translating PHP date() for Multilingual Site
Whenever you need to manipulate date/time stamps based on locale, you should use strftime:
switch ($lang) {
case 'en':
setlocale(LC_TIME, 'en_CA.UTF-8');
echo strftime("%B %e, %G");
break;
case 'fr':
setlocale(LC_TIME, 'fr_CA.UTF-8');
echo strftime("%e %B %G");
break;
}
Results:
February 11, 2011 // en
11 février 2011 // fr
Of course, you need to have the locales installed on your system. In Ubuntu per example:
bash-4.1$ sudo locale-gen fr_CA.UTF-8
EDIT in may 2022
strftime()
has been DEPRECATED as of PHP 8.1.0
This is how you should do it:
$fmt = datefmt_create(
'pt_BR', // The output language.
\IntlDateFormatter::FULL,
\IntlDateFormatter::FULL,
pattern: "cccc, d 'de' LLLL 'de' YYYY" // The output formatting.
);
$input = strtotime('20-06-2022');
$output = datefmt_format($fmt, $input);
var_dump($output); // Outputs "segunda-feira, 20 de junho de 2022".
As for strtotime()
use:
- slash (/) for American M/D/Y formatting;
- dash (-) for European D-M-Y formatting and
- period (.) for ISO Y.M.D formatting.
In my sample I am using the european day-month-year formatting.
Click here to see how to format the value of $pattern
parameter in datefmt_create()
.
You must have the intl package installed:
$ sudo apt install php8.1-intl
Change the 8.1
bit to the php version you are working with.
$date = date('F', $start).' '.date('j',$start).', '.date('Y', $start);
That's a rather painful way to go about. The format string in date()
doesn't have to be a single character. This line could be reduced to
$date = date('F j Y');
And given that, you could have a simple
switch($whats_my_locale) {
case 'FR':
$format = 'date format characters for a french date';
break
case 'EN' :
$format = 'format chars for english date'
break
case etc....
default:
$format = 'default date format string here';
}
$local_date_string = date($format, $start);
and off you go.