English | 简体中文 | 繁體中文
查询

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函数
分享链接