简体   繁体   中英

Subtract days from date

How do I take away days from a date? So for example the the second line is the line which doesn't work, just wondering how I would take away days from a date?

 $statement_date = date('Y-m-d', strtotime($date[$selected_int])); 
 $statement_view = $statement_date (-14 days);

You can't use date to substract or add days (hours, minutes etc.), because, as per PHP manual , date :

Returns a string formatted according to the given format

And, well, you can't do what you want to a string.

To achieve what you want going the object oriented style, you have to create a DateTime object first:

$date = new DateTime(); // this will return today OR
$date = new DateTime('2010-05-20'); // this will return the needed date

Next, you may use sub to subtract or add to add a date interval:

$date->sub(new DateInterval('P10D'));
echo $date->format('Y-m-d');

This will output 2016-02-04

Update

You requested your code example:

$date = new DateTime('01/28/2016');
$date->sub(new DateInterval('P14D'));
echo $date->format('m/d/Y');

this will output

01/14/2016

Of course, don't forget to substitute 01/28/2016 for $statement_date

Another way to add/subtract. The below will subtract 14 days (3600*24*14):

$unixRefDate=strtotime($date[$selected_int]);
$unixDate=($unixRefDate-(3600*24*14));
$statement_view=date('Y-m-d', $unixDate);


Care should be taken of the timezone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM