根据PHP中的语言环境为IntlDateFormatter() - > format()生成适当的模式

时间:2015-01-27 14:07:02

标签: php datetime internationalization

我正在尝试依靠IntlDateFormatter 以基于区域设置的格式返回当前日期。对于en_US,这意味着对于it_IT,de_DE,fr_FR ...或者MM / DD / YYYY,对于所有可能的语言环境,这意味着DD / MM / YYYY。

我正在尝试使用我用来检索当前月份名称的相同解决方案:

$formatter = new IntlDateFormatter("it_IT", IntlDateFormatter::FULL, IntlDateFormatter::FULL);
$formatter->setPattern("MMMM");
return $formatter->format($this);

此代码正确返回“January”,“gennaio”等。

问题是,我无法找出以当前语言环境格式获取日期的正确模式。 ICU User Guide提到 DateTimePatternGenerator类,看起来就像这样!但我在PHP中找不到它。

我想避免使用自定义的巨大开关盒,而是依赖内置函数。

必须是纯PHP。

任何帮助?

1 个答案:

答案 0 :(得分:0)

我不确定你是想从ICU本身获取模式,还是只想格式化你的DateTime。这里有两种解决方案。

<强>基础:

您在检索月份名称的实际代码方面做得很好。 IntlDateFormatter是可定制的,它完全取决于你给它的选项。

根据区域设置获取年,月,日的日期:

$locale = "en_GB";
$dateType = IntlDateFormatter::SHORT;//type of date formatting
$timeType = IntlDateFormatter::NONE;//type of time formatting setting to none, will give you date itself
$formatter =new IntlDateFormatter($locale, $dateType, $timeType);
$dateTime = new DateTime("2015-02-28");
echo $formatter->format($dateTime);

会给你

  

28/02/2015

您可以使用IntlDateFormatter的其他选项。有简短,中等,长,完整和无 - 您可以阅读它们并查看示例输出here

来自格式化程序的

Getting pattern

$formatter->->getPattern();

会给你类似的东西

  

DD / MM / YYYY

我希望这会对你有所帮助。很长一段时间我一直在努力做到这一点:)