PHP 意外日期格式化

问题描述 投票:0回答:3

我想为 SQL 格式化一个日期,但是我得到了意想不到的结果:

echo date('Y-m-d H:i:s', strtotime("February 13 2022 10:08 PM")); //2022-02-13 22:08:00
echo date('Y-m-d H:i:s', strtotime("March 23 2022 00:20 AM")); //1970-01-01 00:00:00

有人知道我在这里做错了什么吗?谢谢

php date datetime datetime-format
3个回答
0
投票

这是因为

strtotime("March 23 2022 00:20 AM")
返回 FALSE,因为它是 OMi Shah 指出的无效日期。显然
FALSE
0
函数评估为
date()
,尝试打印
date('Y-m-d H:i:s', FALSE);
并亲眼看看,它会打印
1970-01-01 03:00:00
date('Y-m-d H:i:s', 0);

相同

0
投票

如果你有无效的日期,你需要做错误检查:

$unixTime = strtotime('March 23 2022 00:20 AM');
if ($unixTime === false) {
    // Report error
} else {
    $normalizedString = date('Y-m-d H:i:s', $unixTime);
}

日期解析函数通常过于宽松(例如,

strtotime('PDT')
生成 PDT 时区的当前时间),因此转换回原始格式并查看是否返回相同的值也无妨。

您可能还想修复错误,但这在很大程度上取决于错误的外观以及您想要的解决方案:

'March 23 2022 00:20 AM' // Replace 00:... AM dates with valid representation
'February 31 2023 09:55 PM' // Make it March 3? Throw error?
'(no data)' // Nothing fixable here

0
投票

如果你的目标是修复数据,因为你的任务是使用有缺陷的数据,你可以使用正则表达式来切断任何犯规的

AM
子串。

代码:(演示

$tests = [
    "February 13 2022 10:08 PM",
    "March 23 2022 00:20 AM",
    "April 3 2022 11:20 PM",
    "May 28 2022 12:20 AM",
];

$tests = preg_replace(
    '/(?:0\d|1[01]):\d{2}\K AM/',
    '',
    $tests
);
//var_export($tests);
foreach ($tests as $test) {
    echo date('Y-m-d H:i:s', strtotime($test)) . "\n";
}
© www.soinside.com 2019 - 2024. All rights reserved.