PHP函数名:DateTimeImmutable::setTimestamp()
适用版本:5.5及以上版本
用法:
DateTimeImmutable::setTimestamp()
函数用于设置一个 DateTimeImmutable 对象的时间戳。时间戳是一个表示日期和时间的整数值。
函数语法:
DateTimeImmutable DateTimeImmutable::setTimestamp(int $timestamp)
参数说明:
- $timestamp: 必需。一个整数值,表示日期和时间的时间戳。
返回值:
- 返回一个新的 DateTimeImmutable 对象。
示例:
$timestamp = strtotime("2021-01-01 00:00:00"); // 获取时间戳
$date = new DateTimeImmutable(); // 创建一个新的 DateTimeImmutable 对象
$date = $date->setTimestamp($timestamp); // 设置时间戳
echo $date->format('Y-m-d H:i:s'); // 输出:2021-01-01 00:00:00
在上述示例中,我们首先使用 strtotime()
函数将日期时间字符串转换为时间戳。然后,我们创建了一个新的 DateTimeImmutable 对象,将其时间戳设置为之前获取的时间戳。最后,使用 format()
方法将日期时间格式化为我们想要的格式进行显示。
值得注意的是,DateTimeImmutable对象是不可变的,它的 setTimestamp()
方法会返回一个新的DateTimeImmutable对象,而不是修改原始对象。