查詢

IntlDateFormatter::create()函式—用法及示例

「 建立 IntlDateFormatter 物件,該物件用於格式化日期和時間 」


函式名稱:IntlDateFormatter::create()

適用版本:PHP 5 >= 5.5.0, PHP 7, PHP 8

函式描述:IntlDateFormatter::create() 方法用於建立 IntlDateFormatter 物件,該物件用於格式化日期和時間。

用法:

public static IntlDateFormatter IntlDateFormatter::create (
    string $locale,
    int $datetype,
    int $timetype,
    ?int $timezone = null,
    ?int $calendar = null,
    string $pattern = ""
): IntlDateFormatter|false

引數:

  • $locale:必需,指定日期格式化器的語言環境,例如 "en_US"。
  • $datetype:必需,指定日期的格式型別。可選值有:
    • IntlDateFormatter::FULL:完整的日期格式
    • IntlDateFormatter::LONG:長日期格式
    • IntlDateFormatter::MEDIUM:中等日期格式
    • IntlDateFormatter::SHORT:短日期格式
  • $timetype:必需,指定時間的格式型別。可選值有:
    • IntlDateFormatter::FULL:完整的時間格式
    • IntlDateFormatter::LONG:長時間格式
    • IntlDateFormatter::MEDIUM:中等時間格式
    • IntlDateFormatter::SHORT:短時間格式
  • $timezone:可選,指定時區的整數偏移量(以秒為單位),或者可以使用 DateTimeZone::createTimeZone() 函式返回的 DateTimeZone 物件。
  • $calendar:可選,指定使用的日曆型別。預設為 GregorianCalendar。可選值有:
    • IntlDateFormatter::GREGORIAN:公曆
    • IntlDateFormatter::TRADITIONAL:傳統日曆
  • $pattern:可選,指定自定義的日期時間格式字串。如果未提供,則使用預定義的格式。

返回值:

  • 如果成功建立了 IntlDateFormatter 物件,則返回該物件。
  • 如果建立失敗,則返回 false。

示例:

$formatter = IntlDateFormatter::create(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::MEDIUM,
    'America/New_York'
);

echo $formatter->format(new DateTime()); // 輸出:Monday, January 1, 2022 at 12:00:00 PM Eastern Standard Time

在上面的示例中,我們建立了一個 IntlDateFormatter 物件,使用美國英語環境('en_US'),並設定日期格式為完整格式(IntlDateFormatter::FULL),時間格式為中等格式(IntlDateFormatter::MEDIUM)。我們還指定了時區為紐約時區('America/New_York')。然後,我們使用 format() 方法將當前日期時間格式化為字串,並將其輸出到螢幕上。

補充糾錯
熱門PHP函式
分享連結