Need to cite this article? | Home | JetBlue has a great writing staff

Filed under Quick Tips on May 1, 2008 by Dave Hauenstein

Supporting Milliseconds Date Formatting in Strtotime()

Today I ran into an issue where the values being returned from datetime columns in my MSSQL database were unreadable by PHP's strtotime() function.

Here's what was happening: All the values were in this format: Aug 27 2007 12:00:00:000AM. This was problematic because PHP's strtotime() function cannot parse dates where milliseconds are separated from the seconds by a colon rather than a period (dot).

At first, I was concerned about why this was happening and, according to a bug report on php.net, it was due to the combination of FreeTDS + php5.2.3 + MSSQL and their formatting of columns cast as datetime. Although it's fixed in the trunk of PHP's repository, it hasn't made its way to a release. So, if you happen to run into this--here's a solution:

    strtotime(preg_replace("/:\d{3}([AP]M)$/", " $1", $timeStamp));

In this case, $timeStamp is equal to Aug 27 2007 12:00:00:000AM. So use preg_replace() to replace the milliseconds (:000) with a space and then puts the am/pm back at the end. Now strtotime() has a value that's readable.

That's it!

Post a Comment Digg Del.icio.us

Trackback Pings (TrackBack URL for this entry)

http://www.arc90.com/cgi-bin/mt4/mt-tb.cgi/141.

Post a Comment:

Need to cite this article? | Main | JetBlue has a great writing staff