Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse variable length datetime string which may not have zero padded units ("m/d/yyyy H:i:s" or "mm/dd/yyyy H:i:s")

How would you convert a date string that might be formatted 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.

like image 216
Derek Adair Avatar asked Dec 12 '25 00:12

Derek Adair


2 Answers

strtotime() will have no problem parsing these two datetime formats.

Then just use its return unix timestamp integer with date() to generate the desired format string.

function format_date($date) {
    return date('Y-m-d H:i:s', strtotime($date));
}
like image 128
JAL Avatar answered Dec 13 '25 16:12

JAL


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 :-)

like image 36
prodigitalson Avatar answered Dec 13 '25 17:12

prodigitalson