首页 > 解决方案 > 带斜线的 PHP 日期转换

问题描述

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

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

我正在寻找转换为以下格式:

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

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

标签: phpmysqldatetime

解决方案


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

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

推荐阅读