Convert mssql datetime object to PHP string

I’m grabbing some information from a database and the record is in an MSSQL DateTime format, when I return it, it shows in my array as follows:

[arrayItem] => DateTime Object
        [date] => 2008-06-05 09:14:11
        [timezone_type] => 3
        [timezone] => Europe/London

When I try to extract this as an array (ie $array[arrayItem][date]) I get an error:

Fatal error: Cannot use object of type DateTime as array

I have also tried formatting the data in SQL before it is passed to the PHP, and the strtotime functions and had no joy.

Any recommendations would be very welcome, I’m tearing my hair out with this one!



This has caught me out a couple of times too.

Hopefully this will help you as it has myself 🙂

Here’s the gist of what that page is saying, in case the link goes down.

When querying against a column defined as a datetime, the native PHP SQL Server extension returns a string where as the Microsoft extension returns a DateTime object. So if you are expecting a string, you’ll need to adjust your code accordingly.

It goes on to explain that you can simply add an additional parameter to your requests to the database, specifying that you want your dates to be returned as strings. Simply add the ReturnDatesAsStrings parameter, specifying true.


$connectionParams = array(
    'ReturnDatesAsStrings'=>true  //<-- This is the important line
$conn = sqlsrv_connect('',$connectionParams);

Then you can use $conn as you would regularly for your sqlsrv database connection, only dates will return as strings, instead of DateTime objects.

Alternately, if all you wanted was a timestamp out of the datetime you could call: