English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic PHP Tutorial

Advanced PHP Tutorial

PHP & MySQL

PHP Reference Manual

Usage and Examples of PHP date_sub() Function

PHP Date & Time Function Manual

The date_sub() function subtracts a certain amount of days, months, years, hours, minutes, and seconds from a DateTime object.

Definition and usage

This function isDateTime::sub()alias. This function accepts a DateTime object and a DateInterval object, subtracts the specified time interval from the given DateTime.

Syntax

date_sub$object, $interval)

Parameter

Serial numberParameters and descriptions
1

object (required)

This is a DateTime object that specifies/Represents the date from which you need to subtract the time interval.

2

interval (required)

This is a DateInterval object that specifies the interval to be subtracted.

Return value

The PHP date_sub() function returns a DateTime object from which the given interval is subtracted. If it fails, this function will return a boolean valuefalse.

PHP version

The date_sub() function was originally introduced in PHP version5.3introduced in PHP version 5.2.0 and can be used in all higher versions.

Online example

The following example demonstratesdate_sub()Usage of the function.-

<?php
   //Create a DateTime object
   $date = date_create("2019-09-25");
   //Add a time interval to the date
   $res = date_sub($date, new DateInterval('PT10H30S'));   
   //Format the date to print
   $format = date_format( $res, "Y-m-d H:i:s");
   print($format);
?>
Test and see‹/›

Output result

2019-09-24 13:59:30

Online example

The following example uses this function to create an interval and subtract the created interval from the date

<?php
   $date = date_create("1989-09-26");
   $interval = date_interval_create_from_date_string('1025 days');
   $res = date_sub($date, $interval);   
   $format = date_format( $res, "Y-m-d");
   print($format);   
?>
Test and see‹/›

Output result

1986-12-06

Online example

Now, let's try to add an interval with year, month, and day-

<?php
   //Create a DateTime object
   $date = date_create("1989-09-26");
   //Add an interval to the date
   $res = date_sub($date, new DateInterval('P29Y2M5D'));   
   //Format the date to print
   $format = date_format( $res, "Y-m-d");
   print($format);
?>
Test and see‹/›

Output result

1960-07-21

Online example

from date1995-05-07minus 150 Days:

<?php
   $date = date_create('1995-05-07')
   $interval = date_interval_create_from_date_string('150 days');
   $date->sub($interval);
   >print($date -> format('Y-m-d'));
?>
Test and see‹/›

This produces the following result-

1994-12-08