Skip to content
Advertisement

How to convert a Datetime string to standard mysql

I made a function in php to convert date and time coming from a txt to the mysql standard. But she is turning the month wrong. I have tried all these conversions but to no avail. I would like your help because I don’t know what else to do.

    function convertstringdate('05/02/202116:43:49'){
        
    $date = new DateTime($datetime);
      return date_format($date, "Y-m-d H:i:s");
    
    
    }
or

$input = '05/02/202116:43:49'; 
$date = strtotime($input); 
echo date('Y-m-d H:i:s', $date); 

Advertisement

Answer

Since you know the format of your datetime-string I suggest you use createFromFormat() like so:

$string = '05/02/202116:43:49';

$dateTime = DateTime::createFromFormat('d/m/YG:i:s', $string);

var_dump(date_format($dateTime, "Y-m-d H:i:s"));
// output: string(19) "2021-02-05 16:43:49"

Note that I am not sure if 05 or 02 is supposed to be the month in your example, so if this seems wrong to you you might just have to switch around d/m in the format string and make it m/d.

For explanation what character means what poriton of the datetime, see the linked above documentation reference.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement