PHP Function Reference

PHP DateTimeImmutable - modify() Method



The PHP DateTimeImmutable::modify() method creates a new DateTimeImmutable object with timestamp of the given DateTimeImmutable object modified by specified modifier.

Syntax

public DateTimeImmutable::modify(modifier)

Parameters

modifier Required. Specify a date/time string. It should be in valid Date and Time Formats.

Return Value

Returns a new DateTimeImmutable object with modified value on success, otherwise returns false.

Example: Modify by Days, Months & Years

Consider the example below which explains how to modify a given DateTimeImmutable object by specified days, months and years.

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

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

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

  //modify by 1 year 2 months 10 days
  $date_new = $date->modify('1 year 2 months 10 days'); 

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

The output of the above code will be:

Original date: 14-May-2015
Modified date: 24-Jul-2016

Example: Modify by Hours, Minutes and Seconds

The example below illustrates how to modify a given DateTimeImmutable object by specified hours, minutes and seconds.

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

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

  //formatting the datetime to print it
  echo "Original DateTime: ".$date->format("d-M-Y H:i:s")."\n";

  //modify by 5 hours 30 minutes 45 seconds
  $date_new = $date->modify('5 hours 30 minutes 45 seconds'); 

  //formatting the datetime to print it
  echo "Modified DateTime: ".$date_new->format("d-M-Y H:i:s")."\n";
?>

The output of the above code will be:

Original DateTime: 14-May-2015 00:00:00
Modified DateTime: 14-May-2015 05:30:45

Example: Modify by Months

Be cautious, when adding or subtracting months. Consider the example below:

<?php
  //datetime string
  $datetime_string = "31-Jan-2015";

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

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

  //modify by 1 month
  $date_new = $date->modify('+1 month'); 

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

The output of the above code will be:

Original DateTime: 31-Jan-2015
Modified DateTime: 03-Mar-2015

❮ PHP Date and Time Reference