函数名称:DateTimeImmutable::createFromFormat()
函数介绍:该函数通过给定的格式创建一个新的不可变的DateTimeImmutable对象。
用法: DateTimeImmutable DateTimeImmutable::createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )
参数:
- $format:必需,表示时间的格式,使用与date() 函数相同的格式。
- $time:必需,要转换为DateTimeImmutable对象的时间字符串。
- $timezone:可选,一个DateTimeZone对象,表示时区。如果未提供时区,则使用默认时区。
返回值: 成功时,返回一个新的DateTimeImmutable对象;如果失败则返回false。
示例:
- 简单示例:
$dateString = "2020-12-15";
$date = DateTimeImmutable::createFromFormat('Y-m-d', $dateString);
echo $date->format('Y-m-d'); // 输出:2020-12-15
- 使用时区的示例:
$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
- 校验时间格式:
$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()方法来格式化输出日期和时间。