PHP DateTime - setDate() Method
The PHP DateTime::setDate() method sets the date of a DateTime object. The date_date_set() function is an alias of this method.
Syntax
//Object-oriented style public DateTime::setDate(year, month, day) //Procedural style date_date_set(object, year, month, day)
Parameters
object |
Required. For procedural style only: A DateTime object returned by date_create(). |
year |
Required. Specify an integer value representing year of the date. |
month |
Required. Specify an integer value representing month of the date. |
day |
Required. Specify an integer value representing day of the date. |
Return Value
Returns the DateTime object with modified date on success, otherwise returns false.
Example: using both styles
The example below shows the usage of DateTime::setDate() method.
<?php //creating a DateTime object $date = new DateTime(); //setting date using Object-oriented style $date->setDate(2015, 10, 25); //formatting the datetime to print it echo $date->format("d-M-Y")."\n"; //setting date using Procedural style date_date_set($date, 2018, 12, 18); //formatting the datetime to print it echo $date->format("d-M-Y")."\n"; ?>
The output of the above code will be:
25-Oct-2015 18-Dec-2018
Example: Modifying date of a DateTime object
This method can be used to modify date of the DateTime object to a new value. Consider the example below:
<?php //datetime string $datetime_string = "14-May-2015"; //creating a DateTime object $date = new DateTime($datetime_string); //formatting the datetime to print it echo "Original date: ".$date->format("d-M-Y")."\n"; //setting date to a new value $date->setDate(2016, 10, 18); //formatting the datetime to print it echo "Modified date: ".$date->format("d-M-Y")."\n"; ?>
The output of the above code will be:
Original date: 14-May-2015 Modified date: 18-Oct-2016
Example: Adding values exceeding ranges
When values exceeding ranges are passed to this method, they will be added to their parent values. Consider the example below:
<?php //creating a DateTime object $date = new DateTime(); //setting date to a new value $date->setDate(2001, 1, 15); echo $date->format('d-M-Y') . "\n"; //setting date with exceeding range of day - //exceeding days (2 days) will be added $date->setDate(2001, 2, 30); echo $date->format('d-M-Y') . "\n"; //setting date with exceeding range of month - //exceeding months (2 months) will be added $date->setDate(2001, 14, 3); echo $date->format('d-M-Y') . "\n"; ?>
The output of the above code will be:
15-Jan-2001 02-Mar-2001 03-Feb-2002
❮ PHP Date and Time Reference