PHP 中日期时间的交互化



我正在考虑使用 IntlDateFormatter 类来国际化应用程序中的日期和时间,但手册不太清楚该怎么做。

假设我在应用程序中具有以下格式的日期、时间和日期时间:

2013-07-01 10:00 下午

七月1 @ 10:00下午

七月 1

晚上10:00

我想对其进行本地化,以便它们在另一个语言环境中显示如下:

2013年07月01日 22小时00分

朱伊莱特 1 à 22h00

朱伊莱特 1

22小时00

我该怎么做?我是否创建了八个不同的IntlDateFormatter对象来处理这个问题,因为这似乎不是很直观?

$fmt['en-CA']['dt_long'] = new IntlDateFormatter("en_CA", null, null, null, IntlDateFormatter::GREGORIAN, 'Y-M-dd h:mm a');
$fmt['fr-CA']['dt_long2'] = new IntlDateFormatter("fr_CA", null, null, null, IntlDateFormatter::GREGORIAN, 'Y-M-dd H:mm');
$fmt['en-CA']['dt_short'] = new IntlDateFormatter("en_CA", null, null, null, IntlDateFormatter::GREGORIAN, 'MMM d @ h:mm a');
$fmt['fr-CA']['dt_short2'] = new IntlDateFormatter("fr_CA", null, null, null, IntlDateFormatter::GREGORIAN, 'MMM d 'à' H'h'mm');
...

我想我做错了什么,因为带有类常量的第二个和第三个参数应该是有原因的,对吧?

示例和解释会很棒。

如果你想要这四种特定的格式,你的代码是正确的方式。包裹ICU库的IntlDateFormatter提供了几种标准格式,我相信在每个国家/语言中都有人同意它们。

如果你对他们的思维"标准"没意见,你可以这样称呼这门课,

if (version_compare(PHP_VERSION, '5.3.0', '<')) {
    exit ('IntlDateFormatter is available on PHP 5.3.0 or later.');
}    
if (!class_exists('IntlDateFormatter')) {
    exit ('You need to install php_intl extension.');
}
$mediumShortFormatter = new IntlDateFormatter(
    'fr_CA',
    IntlDateFormatter::MEDIUM,
    IntlDateFormatter::SHORT
);
$longShortFormatter = new IntlDateFormatter(
    'fr_CA',
    IntlDateFormatter::LONG,
    IntlDateFormatter::SHORT
);
$longNoneFormatter = new IntlDateFormatter(
    'fr_CA',
    IntlDateFormatter::LONG,
    IntlDateFormatter::NONE
);
$noneShortFormatter = new IntlDateFormatter(
    'fr_CA',
    IntlDateFormatter::NONE,
    IntlDateFormatter::SHORT
);
$datetime = new DateTime("2013-07-01 22:00:00");
echo $mediumShortFormatter->format($datetime) . "n";
echo $longShortFormatter->format($datetime) . "n";
echo $longNoneFormatter->format($datetime) . "n";
echo $noneShortFormatter->format($datetime) . "n";

上面的代码返回了我这些,

2013-07-01 22:00
1 juillet 2013 22:00
1 juillet 2013
22:00

这些与您问题中的不同。如果您确实需要显示的原始格式,是的,您需要一一指定它们。

在加拿大法语的情况下,您可能非常确定您的格式对您的用户是正确的。但是对于其他区域设置,您会设置这些自定义格式吗?如果标准格式(甚至不是理想的,但)您的用户可以接受,我建议您使用这些默认格式,那么您不必担心其他语言/国家/地区的正确格式。

最新更新