HomeLanguagesPHP | DateTime sub() Function

PHP | DateTime sub() Function

The DateTime::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 DateTime object.

Syntax:

  • Object oriented style:
    DateTime DateTime::sub( DateInterval interval )
  • Procedural style:
    DateTime date_sub( DateTime $object, DateInterval $interval )

Parameters: This function uses two parameters as mentioned above and described below:

  • $object: This parameter holds the DateTime object created by date_create() function.
  • $interval: This parameter holds the DateInterval object.

Return Values: This function returns the DateTime object after subtraction is done on success or False on failure.

Below programs illustrate the DateTime::sub() function in PHP:

Program 1: This program uses DateTime::sub() function to subtract 2 days from given date object.




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


Output:

2019-10-01

Program 2: This program uses DateTime::sub() function to subtract the given interval from date object.




<?php
// PHP program to illustrate DateTime::sub()
// function
  
// Creating a new DateTime() object
$datetime = new DateTime('2019-10-03');
  
// Initialising an interval
$interval = 'P2Y5M2DT0H30M40S';
  
// Calling the sub() function
$datetime->sub(new DateInterval($interval));
  
// Getting a new date time
// format of 'Y-m-d H:i:s'
echo $datetime->format('Y-m-d H:i:s');
  
?>


Output:

2017-04-30 23:29:20

Reference: https://www.php.net/manual/en/datetime.sub.php

RELATED ARTICLES

Most Popular

Dominic
32688 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7057 POSTS0 COMMENTS
Nicole Veronica
12198 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12293 POSTS0 COMMENTS
Shaida Kate Naidoo
7182 POSTS0 COMMENTS
Ted Musemwa
7447 POSTS0 COMMENTS
Thapelo Manthata
7160 POSTS0 COMMENTS
Umr Jansen
7150 POSTS0 COMMENTS