PHP Conference Kansai 2026 (JAPAN)

DateTimeImmutable::setTimestamp

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

DateTimeImmutable::setTimestamp — Sets the date and time based on a Unix timestamp

Опис

#[\NoDiscard(message: "as DateTimeImmutable::setTimestamp() does not modify the object itself")]
public function DateTimeImmutable::setTimestamp(int $timestamp): DateTimeImmutable

Returns a new DateTimeImmutable object constructed from the old one, with the date and time set based on an Unix timestamp.

Параметри

timestamp

Unix timestamp representing the date. Setting timestamps outside the range of int is possible by using DateTimeImmutable::modify() with the @ format.

Значення, що повертаються

Повертає новий об'єкт DateTimeImmutable зі зміненими даними.

Помилки/виключення

Throws a DateObjectError if the object has not been correctly initialized, for example when the constructor of a child class does not call the parent constructor.

Журнал змін

Версія Опис
8.3.0 A DateObjectError is now thrown if the object has not been correctly initialized; previously, an Error was thrown.

Приклади

Приклад #1 DateTimeImmutable::setTimestamp() example

Об'єктно-орієнтований стиль

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

Прогляньте також

+add a note

User Contributed Notes 2 notes

up
1
Philip
5 years ago
This function will not change the value of the DateTimeImmutable object as the method name might suggest. The object, after all, immutable.

<?php
   $dti = new DateTimeImmutable();
   echo $dti->getTimestamp(); // e.g. 123456789
   $dti->setTimestamp(987654321);
   echo $dti->getTimestamp(); // 123456789

   $x = $dti->setTimestamp (987654321);
   echo $x->getTimestamp(); // 987654321
?>
up
-4
lukin dot andrej at gmail dot com
3 years ago
While modifying Datetime with the timezone, the user should be aware that changing the timestamp using "@".\time() is not the same as changing the timestamp using 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