date_sub


 

date_sub

In the following example you will learn about subtracting date and time Function in PHP. This date_sub Function subtracts the specified DateInterval object from the specified DateTime object.

In the following example you will learn about subtracting date and time Function in PHP. This date_sub Function subtracts the specified DateInterval object from the specified DateTime object.

 

date_sub

date_sub alias DateTime::sub functions for subtracting an amount of days, months, years, hours, minutes and seconds from a DateTime object. It subtracts the specified DateInterval object from the specified DateTime object. It returns the modified DateTime.

Description of PHP Date Sub Function

public DateTime DateTime::sub ( DateInterval $interval )
DateTime date_sub ( DateTime $object , DateInterval $interval )

Parameters datetime sub Function PHP

object - Procedural style only: A DateTime object returned by date_create()

interval - The amount of date or time to be subtracted. 

Note: For the date use "P3D", "P3M", "P3Y" or a combination of the three e.g. "P2M5D" (Y = Years, M = Months, D = Days.) MUST BE YEAR MONTH DAY FORMAT "P5Y", "P5M2D", "P5Y4D". For the time use "T3H", "T3M", "T3S" or a combination of the three e.g. "T5H20M" (H = Hours, M = Minutes, S = Seconds). For dateTime use "P5Y2M4DT5H20M". The digit before the letter (NOT P or T) can be any amount.

Example of date_sub() Function in PHP:

<?php

$date = new DateTime("25-Aug-2008 12:05:10");
echo $date->format("d-m-Y H:i:s").'<br />';

date_sub($date, new DateInterval("P5D"));
echo '<br />'.$date->format("d-m-Y").' : 5 Days';

date_sub($date, new DateInterval("P5M"));
echo '<br />'.$date->format("d-m-Y").' : 5 Months';

date_sub($date, new DateInterval("P5Y"));
echo '<br />'.$date->format("d-m-Y").' : 5 Years';

date_sub($date, new DateInterval("P5Y5M5D"));
echo '<br />'.$date->format("d-m-Y").' : 5 Days, 5 Months, 5 Years';

date_sub($date, new DateInterval("P5YT5H"));
echo '<br />'.$date->format("d-m-Y H:i:s").' : 5 Years, 5 Hours';

?>

Ads