PHP Function Reference

PHP DateTimeImmutable - setTimestamp() Method



The PHP DateTimeImmutable::setTimestamp() method returns a DateTimeImmutable object with date and time set to the specified Unix timestamp.

Note: Unix timestamp indicates the number of seconds since midnight of January 1, 1970 (Gregorian Calendar).

Syntax

public DateTimeImmutable::setTimestamp(timestamp)

Parameters

timestamp Required. Specify a Unix timestamp representing the date.

Return Value

Returns a new DateTimeImmutable object with date and time set to the specified Unix timestamp on success, otherwise returns false.

Example: Sets the date and time

The example below shows the usage of DateTimeImmutable::setTimestamp() method.

<?php
  //datetime string
  $datetime_string = "14-May-2015 5:10";

  //creating a DateTimeImmutable object
  $date = new DateTimeImmutable($datetime_string);

  //creating a new DateTimeImmutable object 
  //with date and time set to new value
  $date_new = $date->setTimestamp(1500292845); 

  //formatting the datetime to print it
  echo "Original DateTime: ".$date->format("d-M-Y H:i:s")."\n";
  echo "New DateTime:      ".$date_new->format("d-M-Y H:i:s")."\n";
?>

The output of the above code will be:

Original DateTime: 14-May-2015 05:10:00
New DateTime:      17-Jul-2017 12:00:45

❮ PHP Date and Time Reference