phpdatetimedatetime-formatdate-parsing

Reformat "n/j/Y, G:i:s" date string to "Y-m-d H:i:s"


I'm trying to reformat a datetime string so that I can insert it into my MySQL table's timestamp field.

$string1 = "7/1/2015, 19:42:52"; 
$string2 = "12/12/2015, 1:08:17"; 
$string1 = preg_replace("/\//",'-',$string); 
$string2 = preg_replace("/\//",'-',$string);

this step will like:

7-1-2015, 19:42:52
12-12-2015, 1:08:17

Desired result with zero padded units:

string1 = 2015-07-01 19:42:52
string2 = 2015-12-12 01:08:17

Solution

  • Quick and dirty, but with the result you are already having you can do this:

    echo date('Y-m-d H:i:s', strtotime('7-1-2015, 19:42:52'));
    

    This will give you the expected format: 2015-01-07 19:42:52