简体   繁体   中英

Substruct days stored in variable from date in PHP

As the title says I am trying to subtract a number of days (stored in variable) from a date. I am using the date_sub function. This is the variable which contains the days that I want to substract (integer from a field)

$days=$rowRate['days'];

The function:

$chargedate=date_sub($arrivaldate,date_interval_create_from_date_string($days."days"));

$arrivaldate is the variable that contains the date that i want to substract the $days from.

When I use it, I get the warning date_sub() expects parameter 1 to be DateTime, string given in:\xampp\htdocs\Project\file.php on line 55 .

I think I am messing up with the concatenation but I can not figure this out. Any help would be appreciated.

Try converting the $arrivaldate variable like this before passing it into the date_sub function:

    $arrivaldate = date('Y-M-D', strtotime($arrivaldate));
    
    $chargedate=date_sub(
        $arrivaldate,
        date_interval_create_from_date_string($days."days")
    );

Per the error message you need to create a DateTime object from the $arrivaldate before calling date_sub :

$date = date_create(date('Y-m-d', strtotime($arrivaldate)));
$chargedate = date_sub($date,date_interval_create_from_date_string($days." days"));
echo date_format($chargedate, "Y-m-d");

I added the strtotime because it's not clear what format you are using but it may not be necessary.

The date_sub and date_add functions are only used in practice if a DateInteval is already available. Your task can be solved more efficiently and easily with DateTime::modify() .

$arrivaldate = "2021-08-16";
$days = "5";  //may be also integer

$startDate = date_create($arrivaldate)->modify(-$days."Days");

//test output: 11/08/2021
echo $startDate->format("d/m/Y"); 

Important : The date in $arrivaldate must have a format wich accepted from DateTime.

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