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_getUnix タイムスタンプを取得する

説明

オブジェクト指向型

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

手続き型

Unix タイムスタンプを取得します。

パラメータ

この関数にはパラメータはありません。

戻り値

その日付をあらわす Unix タイムスタンプを返します。

エラー / 例外

タイムスタンプが整数として表現できない場合、 DateRangeError がスローされます。 PHP 8.3.0 より前のバージョンでは、ValueError がスローされていました。また、PHP 8.0.0 より前のバージョンでは同様の場合に false を返していました。 さらに、DateTimeInterface::format()U を指定すると、タイムスタンプは文字列として取得できます。

変更履歴

バージョン 説明
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'); // タイムスタンプをミリ秒で取得
$micro = (int)$date->format('Uu'); // タイムスタンプをマイクロ秒で取得

echo $milli, "\n", $micro, "\n";
?>

上の例の出力は、 たとえば以下のようになります。

1674057635586
1674057635586918

参考

add a note add a note

User Contributed Notes 3 notes

up
36
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
36
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
-1
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