Tigran
Tigran

Reputation: 653

Symfony - Object of class DateTime could not be converted to string

i am having troubles with datetime attribute in my class.

Next code is in my twig template.

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

This is the getPhotoUrl method

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

This is the getPhotoUploadDate method

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

I am getting next error - Warning: strtotime() expects parameter 1 to be string, object given

If i try this way

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

I am getting next error - Catchable Fatal Error: Object of class DateTime could not be converted to string

what i am doing wrong??

Upvotes: 2

Views: 8093

Answers (1)

KhorneHoly
KhorneHoly

Reputation: 4766

The error message

Object of class DateTime could not be converted to string

is all the information you need.

$this->creationDate is an DateTime object, it already contains the Date information.

So instead of date('Y-m-d', strtotime($this->creationDate)) you could easily $this->creationDate->format('Y-m-d').

You're trying to create a new Datestring from another datestring and instead of giving a datestring you're giving the DateTime Object.

Upvotes: 4

Related Questions