如何让PHP使用国际化日期?
问题描述:
我试图让PHP日期工作跨语言。语言代码将根据登录用户的语言设置提供。如何让PHP使用国际化日期?
我想我能做到这一点:
setlocale(LC_ALL, 'de_DE.UTF-8');
echo strftime('%A %B %Y');
但输出是:
Wednesday April 2011
而我本来期望:
Mittwoch April 2011
(四月是在同一英文和德文)
这不是使用strftime
函数的正确方法吗?如果不是,还有其他方法吗?
答
setlocale()返回一个值,可以是FALSE:
返回当前新的语言环境,或者 FALSE如果语言环境功能 不是你的平台上实现,该 指定的语言环境不存在或 类别名称无效。
所以你需要检查返回值。
请注意,语言环境名称因平台而异,de_DE.UTF-8
看起来像一个典型的Unix名称。它是一个Unix服务器吗?如果是这样,请确保计算机实际上已安装了此类语言环境。
答
你可以使用IntlDateFormatter
类(PHP> = 5.3)
引用的IntlDateFormatter::format()
手册页上给出的例子:
$fmt = new IntlDateFormatter("en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN );
echo "First Formatted output is ".$fmt->format(0);
$fmt = new IntlDateFormatter("de-DE" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN );
echo "Second Formatted output is ".$fmt->format(0);
将输出:
First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
Second Formatted output is Mittwoch, 31. Dezember 1969 16:00 Uhr GMT-08:00
答
看起来你缺少一些代码。答案就在这里找到:
http://php.net/manual/en/function.setlocale.php
/* try different possible locale names for german as of PHP 4.3.0 */ $loc_de = setlocale(LC_ALL, '[email protected]', 'de_DE', 'de', 'ge'); echo "Preferred locale for german on this system is '$loc_de'";
?>