HomeLanguagesPHP | date_sub() Function

PHP | date_sub() Function

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

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