array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'zh', ), 'this' => array ( 0 => 'datetime.gettimestamp.php', 1 => 'DateTimeInterface::getTimestamp', ), 'up' => array ( 0 => 'class.datetimeinterface.php', 1 => 'DateTimeInterface', ), 'prev' => array ( 0 => 'datetime.getoffset.php', 1 => 'DateTimeInterface::getOffset', ), 'next' => array ( 0 => 'datetime.gettimezone.php', 1 => 'DateTimeInterface::getTimezone', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'zh', 'path' => 'reference/datetime/datetimeinterface/gettimestamp.xml', ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); ?>
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
DateTimeInterface::getTimestamp -- DateTimeImmutable::getTimestamp -- DateTime::getTimestamp -- date_timestamp_get — 获取 Unix 时间戳
面向对象风格
过程化风格
获取 Unix 时间戳。
此函数没有参数。
返回表示日期的 Unix 时间戳。
如果时间戳不能表示为 int,将抛出 DateRangeError。在 PHP 8.3.0 之前,将抛出
ValueError。并且在 PHP 8.0.0 之前,在这种情况下返回 false
。不过,可以使用
U
格式和 DateTimeInterface::format() 作为 string 检索时间戳。
版本 | 说明 |
---|---|
8.3.0 | 超出范围的异常现在是 DateRangeError。 |
8.0.0 |
这些函数在失败时不再返回 false 。
|
示例 #1 DateTime::getTimestamp() 示例
面向对象风格
<?php
$date = new DateTimeImmutable();
echo $date->getTimestamp();
?>
过程化风格
<?php
$date = date_create();
echo date_timestamp_get($date);
?>
以上示例的输出类似于:
1272509157
如果需要以毫秒或微秒精度检索时间戳,则可以使用 DateTimeInterface::format() 函数。
示例 #2 以毫秒和微秒精度检索时间戳
面向对象风格
<?php
$date = new DateTimeImmutable();
$milli = (int)$date->format('Uv'); // Timestamp in milliseconds
$micro = (int)$date->format('Uu'); // Timestamp in microseconds
echo $milli, "\n", $micro, "\n";
?>
以上示例的输出类似于:
1674057635586 1674057635586918