2025年5月16日 星期五 农历 本月20日小满 证件照排版 | 在线计算器 | 在线算命 | 纸张生成器 | 大乐透机选器 | 双色球机选器 | 股票买卖计算 | 奖状生成器 | 今年过去多少天 | 天数相差计算 | 番茄时钟 | AI提示词 | 2048游戏 | 华容道游戏 | 退休年龄计算
查询

DateTimeImmutable::createFromFormat()函数—用法及示例

「 通过给定的格式创建一个新的不可变的DateTimeImmutable对象 」


函数名称:DateTimeImmutable::createFromFormat() 

函数介绍:该函数通过给定的格式创建一个新的不可变的DateTimeImmutable对象。

用法: DateTimeImmutable DateTimeImmutable::createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )

参数:

  • $format:必需,表示时间的格式,使用与date() 函数相同的格式。
  • $time:必需,要转换为DateTimeImmutable对象的时间字符串。
  • $timezone:可选,一个DateTimeZone对象,表示时区。如果未提供时区,则使用默认时区。

返回值: 成功时,返回一个新的DateTimeImmutable对象;如果失败则返回false。

示例:

  1. 简单示例:
$dateString = "2020-12-15";
$date = DateTimeImmutable::createFromFormat('Y-m-d', $dateString);
echo $date->format('Y-m-d'); // 输出:2020-12-15
  1. 使用时区的示例:
$dateString = "2020-12-15 12:30:45";
$timezone = new DateTimeZone('Asia/Shanghai');
$date = DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $dateString, $timezone);
echo $date->format('Y-m-d H:i:s'); // 输出:2020-12-15 12:30:45
  1. 校验时间格式:
$dateString = "2020-12-15 12:30:45";
$date = DateTimeImmutable::createFromFormat('Y-m-d', $dateString);
if ($date === false) {
    echo "时间格式无效";
} else {
    echo $date->format('Y-m-d'); // 输出:2020-12-15
}

注意事项:

  • 该函数返回一个新的DateTimeImmutable对象,因此原始值不会被更改。
  • $format参数需使用与date()函数相同的格式,详情请参考官方文档:https://www.php.net/manual/en/datetime.format.php
  • 当提供的时间字符串与格式不匹配时,该函数将返回false,需要进行错误处理。
  • 如果未提供时区参数,则会使用默认时区。
  • 可以使用DateTimeImmutable对象的format()方法来格式化输出日期和时间。
补充纠错
热门PHP函数