DonOfDen
DonOfDen

Reputation: 4088

Input Date format Produce Error: Object of class DateTime could not be converted to string

I am trying to increment 1 month from my given date and I am receiving the following error while converting;

Note: Kindly check the comment in the code.

Catchable fatal error: Object of class DateTime could not be converted to string

My Code:

$start_date = '25-05-2015'; // 25th of May 2015
$dateVal = explode("-",$start_date);
$newdate = $dateVal[1].'-'.$dateVal[0].'-'.$dateVal[2].' 00:00:00'; // Converted

$cal_date = DateTime::createFromFormat('m-d-Y H:i:s', $newdate);

$date = new DateTime($cal_date); // To give an standard format for this input only all the above date calculations are made. Pls specify any useful method?

$interval = new DateInterval('P1M');

$date->add($interval);

$currentDate = $date->format('Y-m-d');

How can I convert the date to find the date after one month?

Upvotes: 1

Views: 116

Answers (1)

Kevin
Kevin

Reputation: 41885

Just reuse your $cal_date, no need to feed a new $date object into it:

$start_date = '25-05-2015'; // 25th of May 2015
$dateVal = explode("-",$start_date);
$newdate = $dateVal[1].'-'.$dateVal[0].'-'.$dateVal[2].' 00:00:00'; // Converted

$cal_date = DateTime::createFromFormat('m-d-Y H:i:s', $newdate);

$interval = new DateInterval('P1M');

$cal_date->add($interval);
$currentDate = $cal_date->format('Y-m-d');
echo $currentDate;

The problem is, you're trying to feed a DateTime object instead of a string. It already says it in the error:

$cal_date = DateTime::createFromFormat('m-d-Y H:i:s', $newdate);
// ^ date time object
$date = new DateTime($cal_date); // feeding the DateTime Object into the constructor

Or why not just directly set the format in place, remove that part wherein you're exploding. You don't actually need those:

$start_date = '25-05-2015';
$cal_date = DateTime::createFromFormat('d-m-Y H:i:s', $start_date . ' 00:00:00');
$interval = new DateInterval('P1M');
$cal_date->add($interval);
$currentDate = $cal_date->format('Y-m-d');
echo $currentDate;

Upvotes: 1

Related Questions