PHP设置pl locale后DateTimeImmutable仍返回英文星期缩写问题排查
问题分析与解决方案
核心原因
PHP原生的DateTime/DateTimeImmutable类的format()方法,完全不遵循PHP的Locale设置——它的输出是硬编码的英文格式(基于POSIX标准),和你设置的pl locale没有任何关系。哪怕\Locale::getDefault()返回pl,format('D')依然会输出英文的星期缩写。
解决办法
1. 使用PHP原生IntlDateFormatter(推荐)
这是PHP官方提供的本地化日期处理方案,需要确保环境已安装intl扩展(Symfony 4.4项目通常默认依赖该扩展):
$formatter = new \IntlDateFormatter( 'pl_PL', \IntlDateFormatter::NONE, \IntlDateFormatter::NONE, date_default_timezone_get(), \IntlDateFormatter::GREGORIAN, 'EEE' // 星期缩写,全拼用'EEEE' ); echo $formatter->format(new \DateTimeImmutable());
执行后会输出波兰语的星期缩写,比如周四对应czw。
2. 利用Symfony本地化组件
针对Symfony 4.4项目,直接用框架自带的组件更便捷:
// 注入Symfony\Component\Intl\DateTimeFormatter\DateTimeFormatterInterface $formatted = $dateTimeFormatter->format( new \DateTimeImmutable(), 'EEE', // 星期缩写 'pl_PL' ); echo $formatted;
如果是在Twig模板中使用:
{{ date()|localizeddate('none', 'none', 'pl_PL', null, 'EEE') }}
注意事项
- 检查
intl扩展状态:可以通过php -m | grep intl命令验证,或者在代码里用extension_loaded('intl')判断。 - 若需要完整星期名称,将格式化符从
EEE替换为EEEE即可。
内容的提问来源于stack exchange,提问作者proggaf
相关产品推荐
相关产品推荐

