用斜杠转换PHP日期
我很难将通过JSON传递的日期字符串转换为PHP格式的日期,我可以在日期计算中使用该日期,并将其以DATETIME格式存储在MySQL中用斜杠转换PHP日期,php,mysql,datetime,Php,Mysql,Datetime,我很难将通过JSON传递的日期字符串转换为PHP格式的日期,我可以在日期计算中使用该日期,并将其以DATETIME格式存储在MySQL中 $passedTime = "30/3/2020 17:7:23:847"; 我希望转换为以下格式: $convertedPassedTime = "2020-3-30 17:07:23"; 我尝试了几种不同的“DateTime::createFromFormat”组合,但不断遇到错误。我无法更改传入数据的格式,因为
$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]));
您还可以选择使其与和兼容,首先用连字符替换斜杠,并删除以冒号开头的毫秒。 然后依赖于正常的
strotime
和date()
函数
$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"
你能展示一下你的最佳尝试吗?以一位数的分钟来回答这个问题。它与任何标准都不匹配,因此您需要了解如何更改
“30/3/2020 17:7:23:847”>>“30/3/2020 17:07:23:847”
,这是否回答了您的问题?请看这是否有意义:这几乎是完美的,在$explodedTime数组上有一个轻微的索引错误。数组索引是0,1和2,而不是2,1,0。见下文<代码>$formattedDate=date(“Y-m-d H:i:s”,STROTIME($explodedDate[2]。”-“$explodedDate[1]。”-“$explodedDate[0]。”。$explodedTime[0]。”:“$explodedTime[1]。”:“$explodedTime[2])代码>哦,是的,就是这样,我不小心把《泰晤士报》上的索引倒过来了,谢谢。但还是很高兴它起作用了。我现在编辑我的答案。