views:

44

answers:

3

How would you convert a datestring that will be formated like...

m/d/yyyy H:i:s or mm/dd/yyyy H:i:s...

and format it like... yyyy-mm-dd H:i:s

I can format either of the two inputs into my desired format, but not both.

+1  A: 

Easiest way would be to simply transform it to unix time first with strtotime then run strftime on it afterwards... not the bes practice but it eliminates alot of the potential format parsing issues :-)

prodigitalson
+1  A: 

How are you formatting it now? If you're certain that those are the only two date formats you'll possibly have as input, then you can explode() it on the forward slashes, then if strlen() returns 1 on the month or the date, add a 0 as you're creating your yyyy-mm-dd string.

However, if you're not guaranteed that those are your only two input formats, then I would use strtotime() to convert it to epoch, then use date() to format it as you desire. A slightly bigger processing hit, but much more universal code.

Brock Batsell
+2  A: 
function format_date($date){
  return date('Y-m-d H:i:s',strtotime($date));
  }

should do the trick.

Alex JL
so simple!!! I forgot how awesome the php date functionality is. I've been using Javascript....
Derek Adair
lol I was using some ridiculously elaborate string replacing to get either of them done.
Derek Adair