PHP Date Convert with slashes

Viewed 1089

I am having difficulty converting a date string passed via JSON into a PHP formatted date which I can use in date calculations and store in DATETIME format in MySQL.

$passedTime = "30/3/2020 17:7:23:847";

I'm looking to convert to the following format:

$convertedPassedTime = "2020-3-30 17:07:23";

I have tried several different combinations of 'DateTime::createFromFormat' but keep coming across errors. I cannot change the format of the incoming data as it comes from an old RFID reader device.

2 Answers

There is most likely a better solution than this, but as quick workaround this works:

$passedDate = "30/3/2020 17:7:23:847";
$explodedDateTime = explode(" ", $passedDate);
$explodedDate = explode("/", $explodedDateTime[0]);
$explodedTime = explode(":", $explodedDateTime[1]);

$formattedDate = date("Y-m-d H:i:s", strtotime($explodedDate[2]."-".$explodedDate[1]."-".$explodedDate[0]." ".$explodedTime[0].":".$explodedTime[1].":".$explodedTime[2]));

You can also chose to make it compatible with the php date and time formats first by replacing the slashes with hyphens, and removing the miliseconds leaded by a colon. Then you rely on the normal strtotime and date() functions.

$passedTime = "30/3/2020 17:7:23:847";

// Replace hyphens with slashes
// Comply with notation:
// Day, month and four digit year, with dots, tabs or dashes: dd [.\t-] mm [.-] YY
$compatible = str_replace('/', '-', $passedTime);

// Remove trailing miliseconds based on position of third (last one) colon
// Comply with notation:
// Hour, minutes and seconds    't'? HH [.:] MM [.:] II
// It's also possible to replace the last colon with a dot to keep the miliseconds
$compatible = substr($compatible, 0, strrpos($compatible, ':'));
// $compatible = "30-3-2020 17:7:23"

$date = strtotime($compatible); 
echo date('Y-m-d H:i:s', $date); // "2020-03-30 17:07:23"
Related