Saturday, November 22, 2025
HomeLanguagesPHP | DateTimeImmutable::sub() Function

PHP | DateTimeImmutable::sub() Function

The DateTimeImmutable::sub() function is an inbuilt function in PHP which is used to subtract a number of days, months, years, hours, minutes and seconds from a created DateTimeImmutable object.

Syntax:

DateTimeImmutable::sub( interval )

Parameters: This function accepts a parameter interval which is the number of days or months or years or hours or minutes or seconds which are going to be subtracted from the given DateTimeImmutable object.

Return Values: : This function returns the final datetime after subtraction is done.

Below programs illustrate the DateTimeImmutable::sub() function:

Program 1: This program decreases the days by 2.




<?php
// PHP program to illustrate DateTimeImmutable::sub()
// function
    
// Creating a new DateTimeImmutable() object
$datetimeImmutable = new DateTimeImmutable('2019-10-07');
  
// Initialising a interval of 2 days
$interval = 'P2D';
  
// Calling the DateTimeImmutable::sub() function
$a = $datetimeImmutable->sub(new DateInterval($interval));
  
// Getting a new date time
// format of 'Y-m-d'
echo $a->format('Y-m-d');
?>


Output:

2019-10-05

Program 2: This program decreases the month by 5.




<?php
// PHP program to illustrate DateTimeImmutable::sub()
// function
    
// Creating a new DateTimeImmutable() object
$datetimeImmutable = new DateTimeImmutable('2019-10-07');
  
// Initialising a interval of 5 months
$interval = 'P5M';
  
// Calling the DateTimeImmutable::sub() function
$a = $datetimeImmutable->sub(new DateInterval($interval));
  
// Getting a new date time
// format of 'Y-m-d'
echo $a->format('Y-m-d');
?>


Output:

2019-05-07

Reference
https://devdocs.io/php/datetimeimmutable.sub

RELATED ARTICLES

Most Popular

Dominic
32407 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6784 POSTS0 COMMENTS
Nicole Veronica
11931 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11999 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6863 POSTS0 COMMENTS
Umr Jansen
6848 POSTS0 COMMENTS