大网数据广告活动
PHP 语言与运行手册

DateTimeInterface::getTimestamp · 获取 Unix 时间戳

· 52CE 我爱测

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

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 function DateTimeInterface::getTimestamp(): int
public function DateTimeImmutable::getTimestamp(): int
public function 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();

以上示例的输出类似于:

1272509157

过程化风格

<?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

参见

来源:PHP Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
PHP Documentation Group
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。