持久化symfony2实体datetime字段:类DateTime的对象无法转换为int

时间:2015-03-12 03:25:22

标签: php symfony datetime doctrine-orm

我有一个拥有此字段的实体:

  /**
   * @var \DateTime
   *
   * @Groups({"list", "details"})
   * @ORM\Column(name="timestamp", type="datetime")
   */
  private $timestamp;

我有以下代码:

$date = new \DateTime();
$myentity->setTimestamp($date); //Fails
$myentity->setTimestamp($date->getTimestamp()); //Also fails

我收到以下错误:

[Symfony\Component\Debug\Exception\ContextErrorException]       
  Notice: Object of class DateTime could not be converted to int 

使用symfony和doctrine存储日期时间字段的正确方法是什么?

1 个答案:

答案 0 :(得分:-1)

有可能比面向对象方法:$date = new \DateTime(); $myentity->setTimestamp($date->getTimestamp());将被ORM覆盖。

请参阅DateTime::getTimestamp

  1. 如果您尝试使用程序样式:$date = date_create(); $myentity->setTimestamp(date_timestamp_get($date));您有任何满意的结果吗?

    请参阅DateTime::format

  2. 您也可以尝试使用$date = new DateTime(); $myentity->setTimestamp($date->format('U')); // return seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)

    请参阅time()