PHP Function Reference

PHP date_date_set() Function



The PHP date_date_set() function sets the date of a DateTime object. This function is an alias of DateTime::setDate() 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 date_date_set() function.

<?php
  //creating a DateTime object
  $date = date_create();

  //setting date using Object-oriented style
  $date->setDate(2015, 10, 25); 

  //formatting the datetime to print it
  echo date_format($date, "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($date, "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 function 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 = date_create($datetime_string);

  //formatting the datetime to print it
  echo "Original date: ".date_format($date, "d-M-Y")."\n";

  //setting date to a new value
  date_date_set($date, 2016, 10, 18); 

  //formatting the datetime to print it
  echo "Modified date: ".date_format($date, "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 function, they will be added to their parent values. Consider the example below:

<?php
  //creating a DateTime object
  $date = date_create();

  //setting date to a new value
  date_date_set($date, 2001, 1, 15);
  echo date_format($date, 'd-M-Y') . "\n";

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

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