输入日期格式生成错误:类DateTime的对象无法转换为字符串

时间:2015-05-11 13:23:20

标签: php datetime

我试图从我的指定日期开始增加1个月,并且在转换时收到以下错误;

注意:请检查代码中的注释。

  

捕获致命错误:无法转换类DateTime的对象   字符串

我的代码:

$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');

如何转换日期以查找一个月后的日期?

1 个答案:

答案 0 :(得分:1)

只需重复使用$cal_date,无需向其中提供新的$date对象:

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

问题是,您尝试提供DateTime对象而不是字符串。它已经在错误中说出来了:

$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

或者为什么不直接设置格式,删除那些爆炸的部分。你实际上并不需要那些:

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