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

如何使用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;
?>

我想从日期中获取日,月和年但不起作用。 我总是收到错误: p>

致命错误:在第4行的printtest.php中的非对象上调用成员函数format() p> \ n blockquote>

这是我的 printtest.php code>代码。 我收到了一个错误。 如何解决这个问题? 查看现场演示此处。 p>

 &lt;  ?php 
 $ dob = $ _POST ['dob']; 
 $ date = DateTime :: createFromFormat(“Ymd”,'$ dob'); 
 $ year1 = $ date-&gt; format(“Y”  ); 
 $ day1 = $ date-&gt;格式(“d”); 
 $ mon3 = $ date-&gt;格式(“m”); 
 echo $ year1; 
?&gt; 
   pre> 
  div>

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;
?>