natinusala natinusala - 2 years ago 102
PHP Question

strftime encoding issue within format string

I'm trying to format dates using

and a French locale for
. I've got an encoding issue, not for the dates themselves but within the format string.

Let me explain ; in my examples,
%A %d %B à %Hh%M
and the
date is somewhere in august.

I first started with this :
strftime($format, $time)
, and it gave me
Vendredi 05 Ao�t à 11h57

I wanted to solve the encoding problem, so I did this :
utf8_encode(strftime($format, $time))
, which gave me this :
Vendredi 05 Août à 11h57

You can see that the encoding problem on
is gone, but one has appeared on the
of the format string.

How may I fix this ? Do I have to do
utf8_encode(strftime("%A %d %B", $time)) . " à " . utf8_encode(strftime("%Hh%M", $time))
or is there a cleaner way ?

Thanks !

Answer Source

Given the output examples above, I'd guess that your source file is UTF-8 (so the à is UTF-8 encoded) and your output HTML is also sent with a UTF-8 character set. The problem seems to be that you're using a non-UTF-8 French locale so the returned string from strftime() is not UTF-8 but rather something like ISO-8859-1 or ISO-8859-15.

So either you stick with the cumbersome approach of converting only parts of your result string to UTF-8 (utf8_encode(strftime("%A %d %B", $time)) . " à " . utf8_encode(strftime("%Hh%M", $time)) or you select a UTF-8 variation of the French locale. On Linux that should be something like fr_FR.UTF-8.

The following works on Mac OS X (with shipped PHP 5.5):

setlocale(LC_TIME, 'fr_FR.UTF-8');
echo strftime('%A %d %B à %Hh%M', strtotime('2016-08-12 12:00:00'));

// Vendredi 12 août à 12h00

Also check the locals supported by your system running locale -a on the command line.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download