Share Microsoft SQL Server Driver for PHP returns DateTime Object

March 13th, 2010 by Erik

Interesting gotcha feature with the Microsoft SQL Server extension for PHP on Windows. 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.

I personally like to have my dates and times as timestamps but you can rework this for your needs. I could see extending this return a formatting date string instead of a timestamp or perhaps include a date format parameter to the function.

public function date_normalizer($d){
	if($d instanceof DateTime){
		return $d->getTimestamp();
	} else {
		return strtotime($d);
	}
}

Another route is to pass in the connection parameters necessary to make the conversion at the driver level. This is done by adding the “ReturnDatesAsStrings” parameter to your connection parameters.

$connectionParams = array(
	'USR'=>'user',
	'PASS'=>'pass',
	'Database'='myDatabase',
	'ReturnDatesAsStrings'=>true,
	'Timeout'=>1,
);
$conn = sqlsrv_connect('127.0.0.1',$connectionParams);

You should follow me on Twitter.

Tags: , , , , ,

Not ready to comment, but still found it valuable?

2 Responses to “Microsoft SQL Server Driver for PHP returns DateTime Object”

  1. Rodrigo Saling Rodrigo Saling Says:

    Thanks dude, using the second piece of code here. SQL return error with the Timeout parameter, but I thinks its working after all.

  2. Mark Mark Says:

    Hi, like you, I always suggest storing dates and times as timestamps for ease of date calculation…

    As an aside, have you ever tried the Mono Project(?) .Net on Linux ;)

    Regards
    Mark

Leave a Reply

© 1998-2008 AF-Design, All rights reserved.