Correct a text string to date format


Hello everyone I have the following string 09/20/2018 12:21 PM which I want to convert to date format to insert it into a column of a MySQL database that has datetime I tried with the function strtotime but the result what I get is from an integer something like int(201021) is not converted to insert it.

asked by Luis Miguel 20.09.2018 в 19:26

1 answer


To convert that format to SQL format, try this.

function conv_fecha($string) {
    $date = DateTime::createFromFormat('m/d/Y h:i A', $string);
    return $date->format('Y-m-d H:i:s');

echo conv_fecha('09/20/2018 12:21 PM');
echo conv_fecha('10/02/2018 01:21 AM');


2018-09-20 12:21:00
2018-10-02 01:21:00

[Edit] If the time format is 0 on the left (1:25 PM), use "g" minuscule instead of "h", following what the PHP documentation says link

answered by 20.09.2018 / 19:40