PHP 8.1.28 Released!

DateTimeInterface::getTimestamp

DateTimeImmutable::getTimestamp

DateTime::getTimestamp

date_timestamp_get

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTimeInterface::getTimestamp -- DateTimeImmutable::getTimestamp -- DateTime::getTimestamp -- date_timestamp_get获取 Unix 时间戳

说明

面向对象风格

public DateTimeInterface::getTimestamp(): int
public DateTimeImmutable::getTimestamp(): int
public DateTime::getTimestamp(): int

过程化风格

获取 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

参见

add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top