John
John

Reputation: 952

Fatal error when trying to convert dateformat

I have a datepicker with the format: d/m/Y.

I am trying to send the date from the datepicker to my database in the format: Y-m-d.

I am using the following script for it:

$myDateTime1 = DateTime::createFromFormat('d/m/Y', $single_cal4);
$newSingle_cal4 = $myDateTime1->format('Y-m-d');

When I run this script I get the following error:

Fatal error: Call to a member function format() on a non-object in /send1.php on line 80

Line 80 is:

$newSingle_cal4 = $myDateTime1->format('Y-m-d');

I am sure that this script is working for other pages. Does someone know why I am getting this error and how I can fix it=

Upvotes: 0

Views: 98

Answers (3)

Ravinder Reddy
Ravinder Reddy

Reputation: 3879

You should pass the second parameter $single_cal4 as String to function createFromFormat() . Reference http://php.net/manual/en/datetime.createfromformat.php

The below code will give error because second parameter not passed as string

 $myDateTime1 = DateTime::createFromFormat('d/m/Y', 23/06/2000);
 echo $newSingle_cal4 = $myDateTime1->format('Y-m-d');

When it is passed as string, you get the desired result

$myDateTime1 = DateTime::createFromFormat('d/m/Y', '23/06/2000');
echo $newSingle_cal4 = $myDateTime1->format('Y-m-d');

Out put: 2000-06-23

I hope this will give some idea to debug.

Upvotes: 0

Huy Trịnh
Huy Trịnh

Reputation: 753

Alex Howansky is right, you should check if $myDateTime1 is valid or not by do this:

try {
    $myDateTime1 = DateTime::createFromFormat('d/m/Y', $single_cal4);
} catch (Exception $e) {
    echo $e->getMessage();
}
$newSingle_cal4 = $myDateTime1->format('Y-m-d');

Upvotes: 1

Alex Howansky
Alex Howansky

Reputation: 53573

This simply means that $myDateTime1 is not an object, which means that DateTime::createFromFormat('d/m/Y', $single_cal4); failed, which means that $single_cal4 is not a valid date. See the docs for createFromFormat() regarding what it returns when it encounters an error. You'll want to add a check to ensure it worked correctly.

Upvotes: 2

Related Questions