• PHP Video Tutorials

PHP date_time_set() Function



Definition and Usage

The date_time_set() function is an alias of the DateTime::setTime() function. Using this, you can (re)set the time of a DateTime object.

Syntax

date_time_set($object, $hours, $minutes, $seconds, $microseconds)

Parameters

Sr.No Parameter & Description
1

object(Mandatory)

This is a DateTime object to which you need to set the date.

2

hours(Mandatory)

This is an integer value representing the hour of the time to be set.

3

minute(Mandatory)

This is an integer value representing the minute of the time to be set.

4

seconds(Optional)

This is an integer value representing the seconds of the time to be set.

5

microseconds(Optional)

This is an integer value representing the microseconds of the time to be set.

Return Values

PHP date_time_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.2.0 and, works with all the later versions.

Example

Following example demonstrates the usage of the date_time_set function −

Live Demo
<?php
   //Creating a date
   $date = new DateTime();
   //Setting the date
   date_time_set($date, 7, 20, 35);   
   print("Date: ".date_format($date, "Y/m/d H:i:s"));
?>

This will produce following result −

Date: 2020/05/10 07:20:35

Example

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

<?php
   //Date string
   $date_string = "25-09-1989 10:42:12";
   //Creating a DateTime object
   $date_time_Obj = date_create($date_string);
   print("Original Date: ".date_format($date_time_Obj, "Y/m/d H:i:s"));
   print("\n");
   //Setting the date
   $date = date_time_set($date_time_Obj, 6, 36, 3 );   
   print("Modified Date: ".date_format($date, "Y/m/d H:i:s"));
?>

This will produce following result −

Original Date: 1989/09/25 10:42:12
Modified Date: 1989/09/25 06:36:03

Example

While invoking this function if you pass the day and month values exceeding their range, they will be added to their parent values −

Live Demo
<?php
   //Creating a date
   $date = new DateTime();
   //Setting the date
   date_time_set($date, 24, 15, 36);   
   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

Example

$dateSrc = '2007-04-19 12:50 GMT';
$dateTime = date_create( $dateSrc);;
$retval = date_time_set( $dateTime, 20, 40, 10);
   
echo 'DateTime::format(): '.$dateTime->format('Y:M:D:H:i:s');
echo "\n";

# Using second function.
$dateTime = new DateTime($dateSrc);
$retval = $dateTime->setTime(20, 56,6);
   
echo 'DateTime::format(): '.$dateTime->format('Y:M:D:H:i:s');

This will produce the following result −

DateTime::format(): 2007:Apr:Thu:20:40:10
DateTime::format(): 2007:Apr:Thu:20:56:06
php_function_reference.htm
Advertisements