• PHP Video Tutorials

PHP date_date_set() Function



Definition and Usage

The date_date_set() function is an alias of the DateTime::setDate(). Using this, you can (re)set the date of a DateTime object.

Syntax

date_date_set($object, $year, $month, $day)

Parameters

Sr.No Parameter & Description
1

object(Mandatory)

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

2

year(Mandatory)

This is an integer value representing the year of a date.

3

month(Mandatory)

This is an integer value representing the month of a date.

4

day(Mandatory)

This is an integer value representing the day of a date.

Return Values

PHP date_date_set() function returns the DateTime object with modified 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_date_set function −

Live Demo
<?php
   //Creating a date
   $date = new DateTime();
   //Setting the date
   date_date_set($date, 2019, 07, 17);   
   print("Date: ".date_format($date, "Y/m/d"));
?>

This will produce following result −

Date: 2019/07/17

Example

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

<?php
   //Date string
   $date_string = "25-09-1989";
   //Creating a DateTime object
   $date_time_Obj = date_create($date_string);
   print("Original Date: ".date_format($date_time_Obj, "Y/m/d"));
   print("\n");
   //Setting the date
   $date = date_date_set($date_time_Obj, 2015, 11, 25 );   
   print("Modified Date: ".date_format($date, "Y/m/d"));
?>

This will produce following result −

Original Date: 1989/09/25
Modified Date: 2015/11/25

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_date_set($date, 2019, 15, 17);   
   print("Date: ".date_format($date, "Y/m/d"));
?>

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

Date: 2020/03/17

Example

$dateSrc = '2005-04-19 12:50 GMT';
$dateTime = date_create( $dateSrc);;
# Now set a new date using date_date_set();
date_date_set( $dateTime, 2000, 12, 12);
   
echo "New Formatted date is ". $dateTime->format("Y-m-d\TH:i:s\Z");
echo "
"; # Using second function. $dateTime = new DateTime($dateSrc); $dateTime->setDate( 1999, 10, 12); echo "New Formatted date is ". $dateTime->format("Y-m-d\TH:i:s\Z");

This will produce the following result −

New Formatted date is 2000-12-12T12:50:00Z
New Formatted date is 1999-10-12T12:50:00Z
php_function_reference.htm
Advertisements