【问题标题】:PHP Date Convert with slashes带斜线的 PHP 日期转换
【发布时间】:2020-10-19 11:02:13
【问题描述】:

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

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

我希望转换为以下格式:

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

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

【问题讨论】:

  • 你能展示你最好的尝试吗?
  • 个位数分钟的问题。它不符合任何标准,所以你需要找到如何更改"30/3/2020 17:7:23:847" >> "30/3/2020 17:07:23:847"
  • 这能回答你的问题吗? Converting string to Date and DateTime
  • 请看这有意义吗:phpize.online/…

标签: php mysql datetime


【解决方案1】:

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

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

【讨论】:

  • 这几乎是完美的,$explodedTime 数组有一个轻微的索引错误。数组索引是 0,1 和 2,而不是 2,1,0。见下文。 $formattedDate = date("Y-m-d H:i:s", strtotime($explodedDate[2]."-".$explodedDate[1]."-".$explodedDate[0]." ".$explodedTime[0].":".$explodedTime[1].":".$explodedTime[2]));
  • 哦,是这样的,我不小心把索引倒退了,谢谢。不过还是很高兴它奏效了。我现在将编辑我的答案。
【解决方案2】:

您还可以选择首先使其与php datetime formats 兼容,方法是将斜杠替换为连字符,并删除以冒号开头的毫秒。 然后你依赖正常的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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 2022-07-31
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    相关资源
    最近更新 更多