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

DateTime::setTimestamp()函数—用法及示例

「 设置 DateTime 对象的 Unix 时间戳 」


函数名:DateTime::setTimestamp()

函数介绍:DateTime::setTimestamp() 方法用于设置 DateTime 对象的 Unix 时间戳。

适用版本:该方法从 PHP 5.3.0 起可用,并且在所有版本的 PHP 中可用。

用法:

setTimestamp ( int $unixtimestamp ) : DateTime|false

参数:

  • $unixtimestamp:要设置的 Unix 时间戳。它必须是一个整数。

返回值: 如果成功,该方法会返回一个 DateTime 对象,否则返回 false。

示例:

// 创建一个空的 DateTime 对象
$date = new DateTime();

// 设置时间戳为当前时间
$date->setTimestamp(time());
echo $date->format('Y-m-d H:i:s');  // 输出当前时间

// 设置时间戳为指定时间
$date->setTimestamp(1612345678);
echo $date->format('Y-m-d H:i:s');  // 输出指定时间

在上面的示例中,我们首先创建了一个空的 DateTime 对象 $date。然后,我们使用 setTimestamp() 方法将时间戳设置为当前时间,然后通过 format() 方法将其格式化为 'Y-m-d H:i:s' 的格式进行输出。接着,我们使用 setTimestamp() 方法将时间戳设置为一个特定时间(1612345678),并再次通过 format() 方法进行输出。

请注意,setTimestamp() 方法修改了 DateTime 对象本身,并返回修改后的 DateTime 对象。如果设置时间戳失败(例如,超出有效范围),则返回 false。

补充纠错
上一个函数: DateTime::setTime()函数
下一个函数: DateTime::setTimezone()函数
热门PHP函数
分享链接