Wednesday, August 11, 2010

Convert String to Date in PHP and format it

For this particular case, this is the best solution I've found... I'm getting this from the database on my result set:
2010-08-11 16:00:00.000

First you have to convert it using strtotime(), then using date() you can format it however you want
You can go to the link below for more info on the date function
http://php.net/manual/en/function.date.php

You end up getting something like this
date('Y-m-d',strtotime($variable))

where $variable looks something like this '0000-00-00 00:00:00'...

It should work for pretty much any string which is formatted that way, so if you have something like 2010-10-10 with no time, it will default it to 12AM, and 1969 if you don't have the date but just the time... Play around with it, it's kinda tricky :)