• PHP Video Tutorials

PHP date_sub() Function



Definition and Usage

This function is an alias of the DateTime::sub(). This function accepts a DateTime object and a DateInterval object, subtracts the specified interval to the given DateTime.

Syntax

date_sub$object, $interval)

Parameters

Sr.No Parameter & Description
1

object(Mandatory)

This is a DateTime object specifying/representing the date from which you need to subtract the time interval.

2

interval (Mandatory)

This is a DateInterval object specifying the interval to be subtracted.

Return Values

PHP date_sub() function returns a DateTime object, subtracting the given interval from it. In case of failure, this function returns the boolean value false.

PHP Version

This function was first introduced in PHP Version 5.3.0 and, works with all the later versions.

Example

Following example demonstrates the usage of the date_sub() functio. −

Live Demo
<?php
   //Creating a DateTime object
   $date = date_create("25-09-2019");
   //Adding interval to the date
   $res = date_sub($date, new DateInterval('PT10H30S'));   
   //formatting the date to print it
   $format = date_format( $res, "d-m-Y H:i:s");
   print($format);
?>

This will produce following result −

24-09-2019 13:59:30

Example

Following example creates an interval using this function and subtracts the created interval from a date −

Live Demo
<?php
   $date = date_create("25-09-1989");
   $interval = date_interval_create_from_date_string('1025 days');
   $res = date_sub($date, $interval);   
   $format = date_format( $res, "d-m-Y");
   print($format);   
?>

This will produce following result −

05-12-1986

Example

Now, let us try to add interval with years, months and days −

Live Demo
<?php
   //Creating a DateTime object
   $date = date_create("25-09-1989");
   //Adding interval to the date
   $res = date_sub($date, new DateInterval('P29Y2M5D'));   
   //formatting the date to print it
   $format = date_format( $res, "d-m-Y");
   print($format);
?>

This will produce following result −

20-07-1960

Example

Live Demo
<?php
   $date = date_create('1995-05-07');
   $interval = date_interval_create_from_date_string('150 days');
   $date->sub($interval);
   print($date -> format('d-m-Y'));
?>

This produces the following result −

08-12-1994
php_function_reference.htm
Advertisements