Skip to content

How to Subtract Time from Now in PHP

  • PHP

Subtract Date Time

There are 2 ways to subtract a time interval from a date or add to it in PHP:

Use Function strtotime

Using strtotime function to subtract 20 years from now:

$date = date("Y-m-d", strtotime("-20 year", time()));
echo $date;

For example, today is your 20th birthday and the following code example can show the exact date of your birth in a HTML Form:

$date = date("Y-m-d", strtotime("-20 year", time()));
echo <<< _BIRTH
<form method='post' action='happy_birthday.php'>
<input required size="10" type='date' maxlength='10' name='birthday' value='$date' />

Use Object DateTime

First of all, construct a new DateTime object and then use DateInterval to subtract a period of time from the object.

$date_obj = new DateTime();
$date_obj -> sub(new DateInterval('P20Y'));
$date = $date_obj -> format('Y-m-d');
echo $date;

Leave a Reply

Your email address will not be published. Required fields are marked *