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


Generate appropriate pattern for IntlDateFormatter()->format() based on locale in PHP

我试图依靠IntlDateFormatter以基于语言环境的格式返回当前日期。这意味着 DD/MM/YYYY 表示 it_IT、de_DE、fr_FR...或 MM/DD/YYYY 表示en_US,依此类推表示所有可能的区域设置。

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

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

此代码正确返回"一月"、"根奈奥"等。

问题是,我无法找出正确的模式来获取当前区域设置格式的日期。ICU 用户指南提到了 DateTimePatternGenerator 类,看起来很像!但我在 PHP 中找不到它。

我想避免使用定制的、巨大的开关盒,而是依靠内置功能。

它必须是纯 PHP。

有什么帮助吗?

我不确定您是想从 ICU 本身获取模式,还是只是格式化您的日期时间。在这里,您有两种解决方案。

基本:

您在检索月份名称的实际代码方面做得很好。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);

会给你

2015/2/28

您可以使用IntlDateFormatter的其他选项。有短,中,长,全和无 - 您可以阅读有关它们的信息并在此处查看示例输出。

从格式化程序获取模式

$formatter->->getPattern();

会给你类似的东西

日/月/年

我希望这对你有帮助。我一直在努力解决这个问题很长时间,以正确地做到这一点:)