The setDate Method of the DateTime Class
The setDate
method changes the date in the DateTime
object. It accepts three parameters: year (an integer), month (an integer from 1 to 12), and day (an integer from 1 to 31). It returns the modified DateTime object.
Syntax
public DateTime::setDate(int $year, int $month, int $day): DateTime
Example
Let's set the new date to March 15, 2023:
<?php
$date = new DateTime();
$date->setDate(2023, 3, 15);
echo $date->format('Y-m-d');
?>
Code execution result:
'2023-03-15'
Example
Automatic correction of invalid dates (January 32nd is converted to February 1st):
<?php
$date = new DateTime();
$date->setDate(2023, 1, 32);
echo $date->format('Y-m-d');
?>
Code execution result:
'2023-02-01'
Example
Setting a date with negative values (transition to the previous year):
<?php
$date = new DateTime();
$date->setDate(2023, -1, 15);
echo $date->format('Y-m-d');
?>
Code execution result:
'2022-11-15'