PHP Conference Japan 2024

DateTimeImmutable::setTimestamp

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

DateTimeImmutable::setTimestamp根據 Unix 時間戳記設定日期和時間

說明

public DateTimeImmutable::setTimestamp(int $timestamp): DateTimeImmutable

傳回一個新的 DateTimeImmutable 物件,它是根據舊的物件建構的,日期和時間則根據 Unix 時間戳記設定。

參數

timestamp

代表日期的 Unix 時間戳記。可以使用 DateTimeImmutable::modify() 方法搭配 @ 格式來設定超出 int 範圍的時間戳記。

回傳值

傳回一個修改過資料的新 DateTimeImmutable 物件。

範例

範例 #1 DateTimeImmutable::setTimestamp() 範例

物件導向風格

<?php
$date
= new DateTimeImmutable();
echo
$date->format('U = Y-m-d H:i:s') . "\n";

$newDate = $date->setTimestamp(1171502725);
echo
$newDate->format('U = Y-m-d H:i:s') . "\n";
?>

上述範例將輸出類似以下的內容:

1272508903 = 2010-04-28 22:41:43
1171502725 = 2007-02-14 20:25:25

另請參閱

新增註解

使用者貢獻的註解 2 則註解

Philip
3 年前
此函式不會更改 DateTimeImmutable 物件的值,即使方法名稱可能暗示會這樣做。畢竟,物件是不可變的。

<?php
$dti
= new DateTimeImmutable();
echo
$dti->getTimestamp(); // 例如 123456789
$dti->setTimestamp(987654321);
echo
$dti->getTimestamp(); // 123456789

$x = $dti->setTimestamp (987654321);
echo
$x->getTimestamp(); // 987654321
?>
lukin dot andrej at gmail dot com
1 年前
當修改帶有時區的 DateTime 時,使用者應該注意,使用「@」.time() 更改時間戳記與使用 setTimestamp() 更改時間戳記並不相同。

$now = new \DateTimeImmutable('August 30, 2023 09:00:00 GMT+01');
$origin = $now->getTimestamp(); // 1693382400
$usingAt = $now->modify('@'.$now->getTimestamp())->getTimestamp(); // 1693378800
$usingSetTimestamp = $now->setTimestamp($now->getTimestamp())->getTimestamp(); // 1693382400

var_dump($usingAt === $origin); // false
var_dump($usingSetTimestamp === $origin); // true
To Top