【问题标题】:Symfony - Object of class DateTime could not be converted to stringSymfony - DateTime 类的对象无法转换为字符串
【发布时间】:2015-10-29 12:19:24
【问题描述】:

我在课堂上遇到了日期时间属性问题。

下一个代码在我的树枝模板中。

<div class="process-photo"><img src="{{ photo.getPhotoUrl }}" /></div>

这是 getPhotoUrl 方法

 public function getPhotoUrl()
    {
        return '/web/uploads/photos/'.$this->getUserId().'/'.$this->getPhotoUploadDate().'/'.$this->getName();
    }

这是 getPhotoUploadDate 方法

public function getPhotoUploadDate() {
    return date('Y-m-d', strtotime($this->creationDate));
    }

我收到下一个错误 - 警告:strtotime() 期望参数 1 是字符串,给定对象

如果我尝试这种方式

public function getPhotoUrl()
    {
        return '/web/uploads/photos/'.$this->getUserId().'/'.$this->creationDate.'/'.$this->getName();
    }

我收到下一个错误 - 可捕获的致命错误:DateTime 类的对象无法转换为字符串

我做错了什么??

【问题讨论】:

  • 错误消息Object of class DateTime could not be converted to string 就是您需要的所有信息。 $this-&gt;creationDate 是一个 DateTime 对象,因此您可以轻松地使用 $this-&gt;creationDate-&gt;format('Y-m-d') 代替 date('Y-m-d', strtotime($this-&gt;creationDate))。为什么要从已有的日期创建日期?
  • 是的,有效!谢谢!
  • 很高兴能帮上忙,我回答了您的问题,如果我的解决方案有效,您可以接受。

标签: php symfony datetime twig


【解决方案1】:

错误信息

DateTime 类的对象无法转换为字符串

是您需要的所有信息。

$this-&gt;creationDate 是一个 DateTime 对象,它已经包含了 Date 信息。

因此,您可以轻松地使用 $this-&gt;creationDate-&gt;format('Y-m-d'),而不是 date('Y-m-d', strtotime($this-&gt;creationDate))

您正在尝试从另一个日期字符串创建新的日期字符串,而不是提供日期字符串,而是提供 DateTime 对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-29
    • 2020-12-25
    • 1970-01-01
    • 2016-11-02
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多