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

phppublic DateTime::setDate(int $year, int $month, int $day): DateTime

Example

Let's set the new date to March 15, 2023:

php<?php
  $date = new DateTime();
  $date->setDate(2023, 3, 15);
  echo $date->format('Y-m-d');
?>

Code execution result:

php'2023-03-15'

Example

Automatic correction of invalid dates (January 32nd is converted to February 1st):

php<?php
  $date = new DateTime();
  $date->setDate(2023, 1, 32);
  echo $date->format('Y-m-d');
?>

Code execution result:

php'2023-02-01'

Example

Setting a date with negative values (transition to the previous year):

php<?php
  $date = new DateTime();
  $date->setDate(2023, -1, 15);
  echo $date->format('Y-m-d');
?>

Code execution result:

php'2022-11-15'

See Also

  • the checkdate function,
    which validates a date
  • the date function,
    which formats a given date
  • the modify function,
    which alters the timestamp by a string in relative format