PHP Function Reference

PHP DateTimeImmutable - setDate() Method



The PHP DateTimeImmutable::setDate() method returns a DateTimeImmutable object with date set to the specified date.

Syntax

public DateTimeImmutable::setDate(year, month, day)

Parameters

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 a new DateTimeImmutable object with date set to the specified date on success, otherwise returns false.

Example: Sets the date

The example below shows the usage of DateTimeImmutable::setDate() method.

<?php
  //datetime string
  $datetime_string = "14-May-2015";

  //creating a DateTimeImmutable object
  $date = new DateTimeImmutable($datetime_string);

  //creating a new DateTimeImmutable object 
  //with date set to new value
  $date_new = $date->setDate(2016, 10, 18); 

  //formatting the datetime to print it
  echo "Original date: ".$date->format("d-M-Y")."\n";
  echo "New date:      ".$date_new->format("d-M-Y")."\n";
?>

The output of the above code will be:

Original date: 14-May-2015
New 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 DateTimeImmutable object
  $date = new DateTimeImmutable();

  //setting date to a new value
  $date_new = $date->setDate(2001, 1, 15);
  echo $date_new->format('d-M-Y') . "\n";

  //setting date with exceeding range of day -
  //exceeding days (2 days) will be added
  $date_new = $date->setDate(2001, 2, 30);
  echo $date_new->format('d-M-Y') . "\n";

  //setting date with exceeding range of month -
  //exceeding months (2 months) will be added
  $date_new = $date->setDate(2001, 14, 3);
  echo $date_new->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