• PHP Video Tutorials

PHP date_timestamp_set() Function


Advertisements

Definition and Usage

The date_timestamp_set() function is an alias of DateTime::setTimestamp. This function accepts a DateTime object and an Unix timestamp as parameters and, sets the specified timestamp to the given object .

Syntax

date_timestamp_set($object, $timestamp)

Parameters

Sr.No Parameter & Description
1

object(Mandatory)

This is a DateTime object.

2

timestamp(Mandatory)

This is an Unix timestamp .

Return Values

PHP date_timestamp_set() function returns the DateTime object with modified (time) value. Incase of failure, this function returns the boolean value false.

PHP Version

This function was first introduced in PHP Version 5.3.0 and, works with all the later versions.

Example

Following example demonstrates the usage of the date_timestamp_set function −

Live Demo
<?php
   $date = new DateTime();
   $res = date_timestamp_set($date, 1505292545);   
   print("Date: ".date_format($res, "Y/m/d H:i:s"));
?>

This will produce following result −

Date: 2017/09/13 08:49:05

Example

Following example creates a DateTime object and modifies its value using the date_timestamp_set() function. −

<?php
   $date = new DateTime();
   $timestamp1 = time() - (23*12*30);   
   $res1 = date_timestamp_set($date, $timestamp1);      
   print("Date: ".date_format($res1, "Y/m/d H:i:s"));
   print("\n");
   $timestamp2 = time() + (23*12*30);
   $res2 = date_timestamp_set($date, $timestamp2);  
   print("Date: ".date_format($res2, "Y/m/d H:i:s"));
?>

This will produce following result −

Date: 2020/05/11 08:57:30
Date: 2020/05/11 13:33:30

Example

As an alternative to this function you can just pass the timestamp value as a string preceded by "@" as a parameter to the DateTime construct −

Live Demo
<?php
  $date = new DateTime("@1495283256");
   print("Date: ".date_format($date, "Y/m/d H:i:s"));?>

Since we have set the month value as 15. Three months are added to the appropriate time −

Date: 2020/05/11 00:15:36
php_function_reference.htm
Advertisements