The setTimestamp Method of the DateTime Class

The setTimestamp method of the DateTime object allows you to set the date and time, using a Unix timestamp (the number of seconds since January 1, 1970). The method modifies the existing date object and returns it for method chaining.

Syntax

phppublic DateTime::setTimestamp(int $timestamp): DateTime

Example

Let's set the date corresponding to the timestamp 1609459200 (January 1, 2021, 00:00:00 UTC):

php<?php
  $date = new DateTime();
  $date->setTimestamp(1609459200);
  echo $date->format('Y-m-d H:i:s');
?>

Code execution result:

php'2021-01-01 00:00:00'

Example

Usage in method chains:

php<?php
  $date = (new DateTime())->setTimestamp(1609459200);
  echo $date->format('Y-m-d');
?>

Code execution result:

php'2021-01-01'

Example

Setting the current time:

php<?php
  $date = new DateTime();
  $date->setTimestamp(time());
  echo $date->format('H:i:s');
?>

Will output the current time, for example:

php'14:25:36'

See Also

  • the date function,
    which formats a Unix timestamp
  • the setDate method,
    which sets the date by parts
  • the getTimestamp method,
    which gets the Unix timestamp from a DateTime object