2013-10-29 58 views
1

我正在尋找使用IntlDateFormatter類來在應用程序中國際化日期和時間,但該手冊不清楚要做什麼。日期時間的國際化在PHP中

假設我有日期,時間和日期時間的應用程序中使用以下格式:

2013-07-01 10:00 PM

7月1日@ 10:00 PM

7月1日

10:00 PM

我婉噸本地化它使得它們被顯示在另一區域設置如下:a 22:00

JUILLET 1

22:00

2013-07-01 22:00

JUILLET 1

我該如何去做這件事?我是否創建了八個不同的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'); 

... 

我覺得我做錯了什麼,因爲與類中的常量第二個和第三個參數應該是有原因的,對不對?

示例和解釋將會很棒。

回答

2

如果你想要這四種特定的格式,你的代碼是正確的方式。 IntlDateFormatter包裝了ICU庫,提供了幾種標準格式,我相信每個國家/地區的語言都有一些人同意。

如果你是好與他們的思維「標準」,你可以調用類的這個樣子,

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 

這些都不是用相同的在你的問題。如果你真的需要你顯示的原始格式,是的,你需要逐一指定它們。

在加拿大法語的情況下,您可能非常確定您的格式對您的用戶而言是正確的。但對於其他語言環境,您是否會設置這些自定義格式?如果標準格式(即使不是理想的,但是)爲您的用戶所接受,我建議您使用這些默認格式,那麼您不必擔心其他語言/國家/地區的格式正確。