php 格式化 DateTime 对象,尊重 Locale::getDefault()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8744952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 05:24:25  来源:igfitidea点击:

Formatting DateTime object, respecting Locale::getDefault()

phpdatetime-format

提问by stoefln

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

我有一个 DateTime 对象,我目前正在通过

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

Which gives me exactly the format I need:

这正是我需要的格式:

Tue 5.3.2012

2012 年 3 月 5 日星期二

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

唯一缺少的一点是正确的语言。我需要TueTuesday)的德文翻译,即DieDienstag)。

This gives me the right locale setting

这给了我正确的语言环境设置

Locale::getDefault()

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

但我不知道如何告诉DateTime::format使用它。

Isn't there a way to do something like:

有没有办法做这样的事情:

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

回答by salathe

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

您可以使用Intl扩展名来格式化日期。它将根据所选语言环境格式化日期/时间,或者您可以使用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

迪。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.

编辑:啊呸!回答了一个古老的问题,因为一些评论将其提升到了列表中!现在至少提到了 Intl 选项。

回答by Jonathan

That's because formatdoes not pay attention to locale. You should use strftimeinstead.

那是因为format不注意语言环境。你应该strftime改用。

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