首页 > 解决方案 > 从 POST 检索日期到 datediff 问题

问题描述

所以我想获取 $dob 的值并将其放入日期差异中以仅获取年份差异。下面的代码工作正常。但我的问题是当我尝试从 $POST 获取 $dob 时出现以下错误: Uncaught Exception DateTime:__construct(); 无法在位置 0 (1) 解析时间字符串 (27-12-2010):意外字符。

有人可以给我一个线索如何解决这个问题,在此先感谢。

    $dob = "27-12-2010";
    $age = $dob;  
    $date = new DateTime($age);
    $now = new DateTime();
    $ageResult = $date->diff($now)->format("%y");

我正在尝试做的事情:

    $age = $_POST["age"];
    $dob = $age;
    $date = new DateTime($dob);
    $now = new DateTime();
    $ageResult = $date->diff($now)->format("%y");

and then put the $ageResult in the DB query

标签: phpdatedate-difference

解决方案


DateTime 构造函数需要知道传递字符串时的格式。使用DateTime::createFromFormat()静态方法。

$dob = "27-12-2010";
$age = $dob;  
$date = DateTime::createFromFormat("d-m-Y", $age);
$now = new DateTime();
$ageResult = $date->diff($now)->format("%y");


推荐阅读