The Modify Method of the DateTime Class

The modify method allows you to modify the date and time of a DateTime object. It accepts a string parameter with a relative date format that specifies how to change the current date/time value.

Syntax

php$datetime->modify(string $modifier);

Example

Add 1 day to the current date:

php<?php
  $date = new DateTime('2023-01-01');
  $date->modify('+1 day');
  echo $date->format('Y-m-d');
?>

Code execution result:

php'2023-01-02'

Example

Subtract 2 weeks from the current date:

php<?php
  $date = new DateTime('2023-01-15');
  $date->modify('-2 weeks');
  echo $date->format('Y-m-d');
?>

Code execution result:

php'2023-01-01'

Example

Set the first day of the next month:

php<?php
  $date = new DateTime('2023-01-20');
  $date->modify('first day of next month');
  echo $date->format('Y-m-d');
?>

Code execution result:

php'2023-02-01'

See Also

  • the date_add function,
    which adds an interval to a DateTime object
  • the date_sub function,
    which subtracts an interval from a DateTime object