Formatting Datetime Object, Respecting Locale::Getdefault()

Formatting DateTime object, respecting Locale::getDefault()

That's because format does not pay attention to locale. You should use strftime instead.

For example:

setlocale(LC_TIME, "de_DE"); //only necessary if the locale isn't already set
$formatted_time = strftime("%a %e.%l.%Y", $mytime->getTimestamp())

Does PHP's DateTime support other formats/locales?

PHP's intl extension has the IntlDateFormatter for this purpose.

$fmt = new IntlDateFormatter(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);

$date = new DateTime;
echo $fmt->format($date);

Convert a DateTime object to a string considering the locale date format

In the strftime() php manual it says

Format the time and/or date according to locale settings. Month and weekday names and other language-dependent strings respect the current locale set with setlocale().

So take a look at setlocale() and change it before using formatted date.

how to format for your datetime locale

%x Preferred date representation based on locale, without the time

%X Preferred time representation based on locale, without the date

example

$dt = DateTime::createFromFormat(DateTime::ISO8601, '2016-07-27T19:30:00Z');
setlocale(LC_TIME, 'en_US');
$usadt = strftime('%x %X', $dt->getTimestamp());
setlocale(LC_TIME, 'pt_BR.UTF-8');
$brazildt = strftime('%x %X', $dt->getTimestamp());
echo "USA Format: $usadt<br>";
echo "Brazil Format: $brazildt<br>";

outputs

USA Format: 07/27/2016 12:30:00 PM

Brazil Format: 27-07-2016 12:30:00

note

I got the locales from this page;

Date function output in a local language

date() is not locale-aware. You should use strftime() and its format specifiers to output locale-aware dates (from the date() PHP manual):

To format dates in other languages,
you should use the setlocale() and
strftime() functions instead of
date().

Regarding Anti Veeranna's comment: he is absolutely right, since you have to be very careful with setting locales as they are sometimes not limited to the current script scope. The best way would be:

$oldLocale = setlocale(LC_TIME, 'it_IT');
echo utf8_encode( strftime("%a %d %b %Y", $row['eventtime']) );
setlocale(LC_TIME, $oldLocale);


Related Topics



Leave a reply



Submit