简体   繁体   中英

Why does DateTime::createFromFormat() returns a boolean and shows data missing error?

When I run these code. I got this error:

Fatal error: Uncaught Error: Call to a member function format() on bool in /Users/xxx/xxx/xxx/www/login/user/save.php:18 Stack trace: #0 {main} thrown in /Users/xxx/xxx/xxx/www/login/user/save.php on line 18.

Is there something wrong with the format() function?

When I use this:

var_dump($tmp);
var_dump(DateTime::CreateFromFormat("m/d/Y", $_POST['start_date']));
var_dump(DateTime::getLastErrors("m/d/Y", $_POST['start_date']));

try to get the error message, it shows:

bool(false)
bool(false)
array(4) {
  ["warning_count"]=> int(0)
  ["warnings"]=> array(0) { }
  ["error_count"]=> int(1)
  ["errors"]=> array(1) {
    [0]=> string(12) "Data missing"
  }
}
$_POST = array_map('stripslashes', $_POST);
$tmp = DateTime::CreateFromFormat("m/d/Y", $_POST['start_date']);
//var_dump....
$start_date = $tmp->format("Y-m-d");
$tmp = DateTime::CreateFromFormat("m/d/Y", $_POST['end_date']);
$end_date = $tmp->format("Y-m-d");

Make sure to begin the function correct case with a lower 'c'.

DateTime::createFromFormat()

$tmp = DateTime::createFromFormat("m/d/Y", $_POST['start_date']);

This method returns either a DateTime object or false on failure. In you your case it looks like $tmp is false (due to wrong function call?), and you can not call format() on a boolean, what the error message says.

So check before applying.

if($tmp) $start_date = $tmp->format("Y-m-d");

The fatal error appears because of data is missing so it returns bool(false). If I type a specific time in the front page form and then front page will show the data: object(DateTime)#7 (3) { ["date"]=> string(26) "2019-09-30 15:09:14.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" }. And it works well to insert to database. Thank you for all your help and guidance!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM