无法将DateTime对象转换为字符串

时间:2013-08-16 01:07:55

标签: php

我正在尝试生成日期(从现在起7个月后) 这是我的代码

$cdate = new DateTime("+7 months");
$cdate->modify("-" . ($cdate->format('j')-1) . " days");
$expiry_date= $cdate->format('Y-m-d');
$expiry_date = strtotime($expiry_date);

给出错误:

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

它正在使用之前......问题是什么?

2 个答案:

答案 0 :(得分:3)

DateTime类没有魔术方法__toString(),因此您不能将此对象用作字符串。

您应该使用getTimestamp()

$cdate = new DateTime("+7 months");
$expiry_date = $cdate->getTimestamp();

答案 1 :(得分:0)

$cdate = new DateTime(+7 months);
$cdate = $cdate->format('Y-m-d');

如果你想要的话,会导致cdate成为一个字符串。