Formatting DateTime object, respecting Locale::getDefault()

拜拜、爱过 提交于 2019-11-26 02:38:21

问题


I have a DateTime object which I\'m currently formating via

$mytime->format(\"D d.m.Y\")

Which gives me exactly the format I need:

Tue 5.3.2012

The only missing point is the correct language. I need German translation of Tue (Tuesday), which is Die (Dienstag).

This gives me the right locale setting

Locale::getDefault()

But I don\'t know how to tell DateTime::format to use it.

Isn\'t there a way to do something like:

$mytime->format(\"D d.m.Y\", \\Locale::getDefault());

回答1:


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())



回答2:


You can use the Intl extension to format the date. It will format dates/times according to the chosen locale, or you can override that with IntlDateFormatter::setPattern().

A quicky example of using a custom pattern, for your desired output format, might look like.

$dt = new DateTime;

$formatter = new IntlDateFormatter('de_DE', IntlDateFormatter::SHORT, IntlDateFormatter::SHORT);
$formatter->setPattern('E d.M.yyyy');

echo $formatter->format($dt);

Which outputs the following (for today, at least).

Di. 4.6.2013


Edit: Ahh boo! Answered an ancient question because some comments bumped it up the list! At least the Intl option is mentioned now.



来源:https://stackoverflow.com/questions/8744952/formatting-datetime-object-respecting-localegetdefault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!