猿问

未捕获的异常: 日期时间::__construct(): 无法解析时间字符串

我正在使用以下函数来计算人们的年龄(以年为单位),从生日日期(欧洲格式DD / MM / YYYY)存储为文本在Wordpress高级自定义字段中


function get_age($birthDate_old) {

    $birthDate = ($birthDate_old);

    return date_diff(new DateTime($birthDate), new DateTime('today'))->y;

}

在大多数情况下,它工作正常,但在某些情况下,我得到了下面的错误:


 Fatal error: Uncaught Exception: DateTime::__construct(): Failed to parse time string (26/01/1958) at position 0 (2): Unexpected character in /home/XXXX/functions.php:99 Stack trace: #0 /home/XXXX/functions.php(99): DateTime->__construct('26/01/1958') #1 /home/XXXX/single.php(69): get_age('26/01/1958') #2 /home/XXX/wp-includes/template-loader.php(98): include('/home/XXX/...') #3 /home/XXX/wp-blog-header.php(19): require_once('/home/XXX/...') #4 /home/XXX/index.php(17): require('/home/monmaire/...') #5 {main} thrown in /home/XXXX/functions.php on line 99

正常工作的数据示例: $age = get_age($birthday);


对于$birthday值 = 05/04/1946,它工作正常,但对于$birthday值 = 26/01/1958,我得到上面的错误。我不明白为什么数据在我看来在2种情况下的格式相同。


你有什么线索吗?


谢谢。问候。


杨__羊羊
浏览 190回答 3
3回答

红颜莎娜

我像这样修复你的函数:function get_age($birthDate_old) {    return date_diff(        DateTime::createFromFormat('d/m/Y', $birthDate_old),         new DateTime('today')    )->y;}在你的情况下,你的日期格式不正确,因为 DateTime 构造函数不知道你是经过一个月还是一天。05/04/1946 还可以。26/01/1958 是不行的,因为 26 默认表示月份。

达令说

据此:https://www.php.net/manual/en/datetime.formats.php// THIS IS INVALID, WOULD IMPLY MONTH == 19$external = "19/10/2016 14:48:21";// HOWEVER WE CAN INJECT THE FORMATTING WHEN WE DECODE THE DATE$format = "d/m/Y H:i:s";$dateobj = DateTime::createFromFormat($format, $external);$iso_datetime = $dateobj->format(Datetime::ATOM);echo "SUCCESS: $external EQUALS ISO-8601 $iso_datetime";26 被视为月。因此,请像上面一样添加到您的日期。$format = "d/m/Y";

收到一只叮咚

问题是日期格式。我相信你正在“/”和“-”之间切换。如果您正在处理大数据,则很难修复整个数据库,因此我最好的建议是进行preg_replace,以便始终确保您从用户/数据库中获取的内容格式正确。在下面找到示例代码。function get_age($birthDate_old) {    $birthDate = ($birthDate_old);    return date_diff(new DateTime($birthDate), new DateTime('today'))->y;}$birthDate = "26/01/1958";$birthDate = preg_replace("(/)", "-", $birthDate);echo get_age($birthDate);我希望它有帮助!让我知道
随时随地看视频慕课网APP
我要回答