我需要将日期值插入到数据库中。 如果我尝试添加一个简单的字符串:
$user->setUpdatedAt('2015-05-31 05:46:23')
ofc 我收到错误,该值必须是 DateTime 对象。
所以我创建了日期时间对象:
$user->setUpdatedAt(new \DateTime($row[29]))
这会创建:
object(DateTime)[1052]
public 'date' => string '2015-05-31 05:46:23' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'Europe/Paris' (length=12)
但是当我尝试冲洗时,我得到:
Call to a member function format() on a non-object
为什么它看不到它是一个对象,而它显然是一个对象?
更新:
实体类是一个简单的 FOSUser 生成的实体:
/**
* @var \DateTime
*/
protected $createdAt;
/**
* @var \DateTime
*/
protected $updatedAt;
/**
* Sets the last update date.
*
* @param \DateTime|null $updatedAt
*
* @return User
*/
public function setUpdatedAt(\DateTime $updatedAt = null)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Returns the last update date.
*
* @return \DateTime|null
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Hook on pre-persist operations.
*/
public function prePersist()
{
$this->createdAt = new \DateTime();
$this->updatedAt = new \DateTime();
}
最佳答案
Doctrine 的日期类型将传入值(DateTime 对象,当然,如果您将字段类型设置为 date、datetime、datetimetz)转换为字符串,并在从数据库获取时将它们转换回 DateTime 对象。尝试找到正确的类(DateTimeType.php、DateTimeTzType.php、DateType.php,根据您的映射类型)并调试 convertToDatabaseValue
方法(例如:dump($value);die ();
),检查即将到来的值。或者使用 xdebug,从 setter 调试到 convertToDatabaseValue
方法。
关于php - 使用 DateTime 设置日期时 Symfony2 格式错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38613729/