Dates & Datetimes when reading from MSSQL in PHP

Posted by on March 28, 2013 in MSSQL, PHP | 0 comments

Dates & Datetimes when reading from MSSQL in PHP

So it gets me every time I try to deal with dates in a query result when I’m getting rows from a MSSQL database in PHP. Normally I work with MySQL when I’m programming in PHP, but I have a hybrid application where .Net is used on the front end, and I do a bunch of back end things using PHP scripts. So here’s the issue. MSSQL doesn’t store things the same way MySQL does. MySQL seems to treat everything like a string. Combine that with PHP’s ability to treat basically anything like a string, and you’ve got a good pair where you can get away without type casting. MSSQL actually type casts some things it stores for you. When you look at Date Times for instance, you’ll see they’re stored as an object. Here’s a dump of the structure.

[time_created] => DateTime Object
(
[date] => 2013-03-27 16:34:41
[timezone_type] => 3
[timezone] => America/New_York
)

Now if you view this in Microsoft SQL Server management studio, you’ll only see the date portion, which is why I never remember that it’s an object. So, if you select it in PHP as a $row, to get the actual date in the string format PHP programmers would be used to, you’d have to do the call below. Assume that the field name is time_created.

$row[‘time_created’]->date

Now notice that we use the -> format because it’s an object, not a 2 dimensional array. The $row is an array because it’s the results of a query.

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>