从POST检索日期到datediff问题中

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

所以我想获取$ 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
php date date-difference
1个回答
0
投票

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");

© www.soinside.com 2019 - 2024. All rights reserved.