DateTime Symfony2保湿/持久

时间:2014-10-02 10:46:54

标签: symfony datetime persistence dateinterval

所以我有这个奇怪的问题,我真的不明白。我只想用两个日期时间“开始时间”和“结束时间”来保湿物体。我通过添加DateInterval(在此示例中为3天)获得结束时间

这是我的控制器

  $datenow = new \DateTime('now');
  var_dump($dateNow);
  $relation->setDateAjout($dateNow); 
  $date = $dateNow;
  $duration=(string)$flower->getDuration();

  $dateEnd=$date->add(new \DateInterval('P'.$duration.'D'));
  var_dump($dateEnd);
  $relation->setDateFin($dateEnd); 

  $em = $this->getDoctrine()->getManager();
  $em->persist($relation);
  $em->flush();
建立者,看起来很好

 /**
     * Set dateAjout
     *
     * @param \DateTime $dateAjout
     * @return Fleur
     */
    public function setDateAjout($dateAjout)
    {
        $this->dateAjout = $dateAjout;

        return $this;
    }


    /**
     * Set dateFin
     *
     * @param \DateTime $dateFin
     * @return Fleur
     */
    public function setDateFin($dateFin)
    {
        $this->dateFin = $dateFin;

        return $this;
    }

什么var转储显示(酷)

object(DateTime)[368]
  public 'date' => string '2014-10-02 12:41:17' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/Paris' (length=12)

object(DateTime)[368]
  public 'date' => string '2014-10-05 12:41:17' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/Paris' (length=12)

phpmyadmin结果(不酷)

2014-10-05 12:41:17
and
2014-10-05 12:41:17

2 个答案:

答案 0 :(得分:3)

问题是您引用了克隆它所需的相同DateTime对象。

$date = clone $dateNow;

http://php.net/manual/fr/language.oop5.cloning.php

答案 1 :(得分:2)

你不能使用相同的DateTime对象并期望不同的结果,你需要克隆它......喜欢:

  $datenow = new \DateTime('now');
  var_dump($dateNow);
  $relation->setDateAjout($dateNow); 
  $date = clone $dateNow; // here is the clonening
  $duration=(string)$flower->getDuration();

  $dateEnd=$date->add(new \DateInterval('P'.$duration.'D'));
  var_dump($dateEnd);
  $relation->setDateFin($dateEnd); 

  $em = $this->getDoctrine()->getManager();
  $em->persist($relation);
  $em->flush();