Open In App

PHP date_sub() Function

Last Updated : 29 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Syntax:

date_sub($object, $interval)

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

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

Return Value: It returns a DateTime object after subtracting the interval. Below programs illustrate the date_sub() function:

Program 1:

php
<?php 
// PHP program to illustrate date_sub() function 

// Create a Date Object
$date = date_create('2018-06-25'); 

// Subtract 5 years from the 25th of June, 2018 
date_sub($date, date_interval_create_from_date_string('5 years')); 

echo date_format($date, 'Y-m-d') . "\n"; 


// Create a Date Object
$date = date_create('2018-06-25'); 

// Subtract 5 month from the 25th of June, 2018
date_sub($date, date_interval_create_from_date_string('5 month')); 

echo date_format($date, 'Y-m-d'). "\n"; 


// Create a Date Object
$date = date_create('2018-06-25'); 

// Subtract 5 days from the 25th of June, 2018 
date_sub($date, date_interval_create_from_date_string('5 days')); 

echo date_format($date, 'Y-m-d'); 

?> 

Output
2013-06-25
2018-01-25
2018-06-20 

Program 2: When invalid date is passed the date_sub function return a warning message.

php
<?php 
// PHP program to illustrate date_sub function 

// The date_sub() function returns warning 
// if 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:

Warning: date_sub() expects parameter 1 to be DateTime, bool given in /home/guest/sandbox/Solution.php on line 8
Warning: date_format() expects parameter 1 to be DateTimeInterface, bool given in /ho...

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


Next Article

Similar Reads