PHP Velho Oeste 2024

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 add a note

User Contributed Notes 3 notes

up
37
heiccih at gmail dot com
10 years ago
In 32-bit system the unix timestamp will overflow if the date goes beyond year 2038 and this method will return false. In 64-bit systems this function will still work as intended. For more information please see http://en.wikipedia.org/wiki/Year_2038_problem.
up
33
Justin Heesemann
13 years ago
Note that for dates before the unix epoch getTimestamp() will return false, whereas format("U") will return a negative number.

<?php
$date
= new DateTime("1899-12-31");
// "-2209078800"
echo $date->format("U");
// false
echo $date->getTimestamp();
?>
up
-6
Julien Bornstein
3 years ago
Please note that DateTime::gettimestamp() will return an integer, but DateTime::format("U") will return a string.

timestamp must always be typed as int because in PHP, timestamps are integers.

eg:
- strftime ( string $format [, int $timestamp = time() ] ) : string
- time() // return int
- ...

So IMHO, as PHP becomes more and more a typed language, avoid using DateTime::format("U") to avoid this kind of errors "strftime() expects parameter 2 to be int, string given"
To Top