Home > Back-end >  Convert English date in French language
Convert English date in French language

Time:11-14

I get a $date from an API in UTC format like 2021-11-13T14:00:14Z.

So using php I convert it to : 13 November 2021

$date = strftime(date('d F Y', strtotime($date);

So now I want to translate it in French.

I am working on local with on macbook pro using MAMP.

My html code setting is :

<html lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

I even forced Local Time to :

setlocale(LC_TIME, 'fr', 'fr_FR', 'fr_FR@euro', 'fr_FR.utf8', 'fr-FR', 'fra'); date_default_timezone_set('Europe/Paris');

But the date remain in english !

Thanks in advance for your help

CodePudding user response:

You're not calling strftime() correctly. The first argument must be a format string. date() returns an already-formatted date, and it doesn't use locales. This works for me:

setlocale(LC_TIME, 'fr', 'fr_FR', 'fr_FR@euro', 'fr_FR.utf8', 'fr-FR', 'fra');
date_default_timezone_set('Europe/Paris');
$date = "2021-11-13T14:00:14Z";
echo strftime('%d %B %Y', strtotime($date));

CodePudding user response:

Solutions based on the IntlDateFormatter class work independently of the local installations of the server. Example as already written in the comment here. When using the class dt, which uses the IntlDateFormatter class, the same format characters can be used for the method formatL as for DateTime::format.

$dt = dt::create('2021-11-13T14:00:14Z');

//UTC -> localTime "2021-11-13 15:00:14"
$dt->setTimeZone('Europe/Paris');  

echo $dt->formatL('l d F Y H:i','fr');
// samedi 13 novembre 2021 15:00

echo $dt->formatL('l d F Y H:i','de');
// Samstag 13 November 2021 15:00

The date string contains the "Z" time zone, which corresponds to UTC. A new time zone can be set with setTimeZone() to get the local time. If the UTC time (here 14:00) is to be displayed, this line must be omitted. The format method (without L) still exists. This method delivers the result as usual in English.

  • Related