用斜线进行PHP日期转换



我很难将通过JSON传递的日期字符串转换为PHP格式的日期,我可以在日期计算中使用该日期,并以DATETIME格式存储在MySQL中。

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

我希望转换为以下格式:

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

我尝试了几种不同的"DateTime::createFromFormat"组合,但总是遇到错误。我无法更改传入数据的格式,因为它来自旧的RFID阅读器设备。

很可能有比这更好的解决方案,但作为快速的解决方案:

$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]));

您还可以选择先将斜杠替换为连字符,然后删除冒号开头的毫秒,使其与php日期和时间格式兼容。然后,您将依赖于正常的strtotimedate()函数。

$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"

最新更新