弘扬国学 · 传承文化
查询

IntlDateFormatter::localtime()函数—用法及示例

「 将给定的日期和时间字符串转换为本地时间 」


函数名称:IntlDateFormatter::localtime() 

适用版本:PHP 5 >= 5.3.0, PHP 7, PHP 8

函数描述:IntlDateFormatter::localtime() 方法用于将给定的日期和时间字符串转换为本地时间。

用法:

public static IntlDateFormatter::localtime(string $text, int &$parse_pos = null, IntlCalendar &$calendar = null) : mixed

参数:

  • $text:要转换的日期和时间字符串。
  • $parse_pos:可选参数,用于存储解析的字符串位置的整数引用。
  • $calendar:可选参数,用于指定要使用的日历对象。

返回值:

  • 如果解析成功,则返回一个表示本地时间的整数。
  • 如果解析失败,则返回 false

示例:

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

// 将日期和时间字符串转换为本地时间
$text = '2021-09-15 12:30:00';
$localTime = $formatter->localtime($text);
echo 'Local Time: ' . date('Y-m-d H:i:s', $localTime) . PHP_EOL;

// 获取解析的字符串位置
$parsePos = null;
$localTime = $formatter->localtime($text, $parsePos);
echo 'Parse Position: ' . $parsePos . PHP_EOL;

// 使用指定的日历对象
$calendar = IntlCalendar::fromDateTime('2021-09-15 12:30:00');
$localTime = $formatter->localtime($text, $parsePos, $calendar);
echo 'Local Time with Custom Calendar: ' . date('Y-m-d H:i:s', $localTime) . PHP_EOL;

以上示例将输出:

Local Time: 2021-09-15 12:30:00
Parse Position: 19
Local Time with Custom Calendar: 2021-09-15 12:30:00

注意:本地时间是相对于指定的时区和日历对象而言的,因此结果可能会因系统设置或输入参数的不同而有所不同。

补充纠错
热门PHP函数
分享链接