Skip to content
Related Articles

Related Articles

Improve Article

PHP | date_sub() Function

  • Last Updated : 28 Nov, 2019
Geek Week

The date_sub() is an inbuilt function in PHP which is used to subtract some days, months, years, hours, minutes, and seconds from given date. The function returns a DateTime object on success and returns FALSE on failure.

Syntax:

date_sub($object, $interval)

Parameters: The date_sub() function accepts two parameters as described below:

  • $object: It is a mandatory parameter which specifies the DateTime object returned by date_create()
  • $interval: It is a mandatory parameter which specifies the DateInterval object which we want to subtract.

Return Value: It returns a DateTime object after subtracting interval.

Below programs illustrate the date_sub() function:
Program 1:






<?php
// PHP program to illustrate date_sub() function
  
// Subtract 5 years from the 25th of June, 2018
$date = date_create('2018-06-25');
date_sub($date, date_interval_create_from_date_string('5 years'));
  
echo date_format($date, 'Y-m-d') . "\n";
  
  
// Subtract 5 month from the 25th of June, 2018
$date = date_create('2018-06-25');
date_sub($date, date_interval_create_from_date_string('5 month'));
  
echo date_format($date, 'Y-m-d'). "\n";
  
// // Subtract 5 days from the 25th of June, 2018
$date = date_create('2018-06-25');
date_sub($date, date_interval_create_from_date_string('5 days'));
  
echo date_format($date, 'Y-m-d');
  
?>

Output:

2013-06-25
2013-01-25
2013-01-20

Program 2: When invalid date is passed the date_sub function gives warnings:




<?php
// PHP program to illustrate date_sub function
  
// date_sub function gives warning when
// we passing invalid date
$date = date_create('2018-25-25');
  
date_sub($date, date_interval_create_from_date_string('5 years'));
  
echo date_format($date, 'Y-m-d') . "\n";
?>

Output:

PHP Warning: date_sub() expects parameter 1 to be DateTime, boolean given in/home
/2662efc623a406b7cb06a7320e7abf50.php on line 8 PHP Warning: date_format() expects parameter 1 to be DateTimeInterface, boolean
given in/home/2662efc623a406b7cb06a7320e7abf50.php on line 9

Reference: http://php.net/manual/en/function.date-sub.php




My Personal Notes arrow_drop_up
Recommended Articles
Page :