Search code examples
phpdate-formatsqlsrv

Adding Days to a date returned through sqlsrv_fetch_array in PHP


Initially when i was using php_msssql extension the following line was working

$test2_date = date('d-M-y', strtotime( "".$res["test_date"]." +".$noofdays." days" ));

$res is array.

Then i changed to php_sqlsrv_53_ts_vc9 extension due to which the above line was not working because "date" doesn't work in this extension so i used "date_format" which works in sqlsrv. My code line was like shown below

$test2_date = date_format(strtotime( "".$res["test_date"]." +".$noofdays." days" ), 'd-M-y');

but the strtotime is not working and hence i get the below error:-

Catchable fatal error: Object of class DateTime could not be converted to string.

what should i use to add days to the date?


Solution

  • date_format take date object as first parameter. So need to create date object with date_create first. Code should be:

    $date = date_create($res["test_date"]);
    date_add($date, date_interval_create_from_date_string(" +" . $noofdays . " days"));
    echo date_format($date, "d-M-y");
    

    UPDATE: If you have date object already then date_create step can be skipped and code will be like:

    date_add($res["test_date"], date_interval_create_from_date_string(" +" . $noofdays . " days"));
    echo date_format($date, "d-M-y");