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.
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.
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 :-)
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.
function format_date($date){
return date('Y-m-d H:i:s',strtotime($date));
}
should do the trick.