如何使用DateTime :: createFromFormat()获取日期?

I want to get day, month, and year from a date but it doesn't work. I always get an error:

Fatal error: Call to a member function format() on a non-object in printtest.php on line 4

This is my printtest.php code. I got an error. How to fix this? Check live demo here.

<?php
    $dob = $_POST['dob'];
    $date = DateTime::createFromFormat("Y-m-d", '$dob');
    $year1 = $date->format("Y");
    $day1 = $date->format("d");
    $mon3 = $date->format("m");
    echo $year1;
?>

Remove the single quotes around your dob variable as Alessandro said, but also, according to your sample site, the input field is in the format d-m-Y, and the format you are passing is Y-m-d.

So change

$date = DateTime::createFromFormat("Y-m-d", '$dob');

to be

$date = DateTime::createFromFormat("d-m-Y", $dob);

Variable interpolation only happens in double-quoted strings so this code is attempeting to parse the string "$dob" as a Y-m-d date, rather than the string contained in the variable $dob. This can be fixed by changing DateTime::createFromFormat("Y-m-d", '$dob') to DateTime::createFromFormat("Y-m-d", "$dob")

Also, since you may not have control over the values posted to your script you should check that DateTime::createFromFormat() returned an object (it returns false on failure) before attempting to operate on its return value, e.g.

$date = DateTime::createFromFormat("Y-m-d", "$dob");
if (!$date)
{
   echo "Invalid dob (YYYY-mm-dd): $dob";
   exit;
}

$year1 = $date->format("Y");
$day1 = $date->format("d");
$mon3 = $date->format("m");
echo $year1;

This way if a dob that can't be parsed as a Y-m-d date is posted you won't get the same fatal error but rather a more useful "Invalid dob" message.

Try the below code to get the Year

<?php
    $dob    = $_POST['dob'];
    $date   = explode("-",$dob);
    $year1  = $date[2];
    echo $year1;
?>