Symfony2 Doctrine:更改DateTime格式

时间:2015-11-20 17:47:50

标签: symfony doctrine-orm

我正在尝试将日期格式更改为Y-m-d H:i:s。这就是我试图做的事情

CollectionController

     date_default_timezone_set('Europe/London');
     $dateAdded = (new \DateTime())->format("Y-m-d H:i:s");
     $collection->setDateAdded($dateAdded);

集合类

/**
 * @ORM\Column(type="datetime", name="date_added")
 */
private $date_added;

public function setDateAdded(DateTime $date_added)
    {
        $this->date_added = $date_added;
        return $this;
    }    

但我有这个错误

传递给CollectionBundle \ Entity \ Collection :: SetDateAdded()的参数1必须是DateTime的实例,给定字符串

3 个答案:

答案 0 :(得分:2)

您的方法的签名是:

public function setDateAdded(DateTime $date_added) {
    $this->date_added = new \DateTime();
    return $this;
}  

您正在尝试传递字符串(格式返回字符串):

public function setDateAdded(DateTime $date_added)
{
    $this->date_added = $date_added;
    return $this;
}    

传递对象引用:

$dateAdded = (new \DateTime())->format("Y-m-d H:i:s");
$collection->setDateAdded($dateAdded);

答案 1 :(得分:0)

非常简单。如果你让public class TestClass extends Application { public Boolean getMedia_state() { return media_state; } public void setMedia_state(Boolean media_state) { this.media_state = media_state; } Boolean media_state; Boolean checkPlaying; public Boolean getNewPermit() { return newPermit; } public void setNewPermit(Boolean newPermit) { this.newPermit = newPermit; } Boolean newPermit; MediaPlayer media; @Override public void onCreate() { super.onCreate(); setMedia_state(true); setNewPermit(true); media = new MediaPlayer(); media = MediaPlayer.create(getApplicationContext(), R.raw.music); } public void musicRestart() { media = MediaPlayer.create(getApplicationContext(), R.raw.music); media.start(); media.setLooping(true); } public void musicPlay() { media.start(); media.setLooping(true); } public boolean checkPlaying() { if (media.isPlaying()) { checkPlaying = true; } else { checkPlaying = false; } return checkPlaying; } public void musicStop() { media.stop(); } } 得到一个字符串作为返回而你没有和DateTime对象。

因此,请在实体中格式化DateTime对象,或删除实体中DateTime的类型提示。

https://secure.php.net/manual/en/datetime.format.php

您可以在此处看到格式化日期format

string

像这样的东西。

抱歉我的错误。如果将字段声明为DateTime,则可以直接设置DateTime对象。如果您从数据库中读取它,则可以对其进行格式化。

答案 2 :(得分:0)

您应该将日期存储为日期时间对象,而不是字符串。格式化它们是视图层的责任,不要改变任何东西,只需将DateTime对象传递给setDateAdded方法,例如:

$collection->setDateAdded(new \DateTime());

并在twig文件中:

{{ object.dateAdded|date('Y-m-d H:i:s') }}