phpstringdatetimedate-conversiondate-parsing

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.


Solution

  • 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));
    }