0

So i have this weird problem i don't really understand. I'm just trying to hydrate an object with two datetimes, "beginning time" and "ending time". I get the ending time by adding a DateInterval (3 days in this example )

here is my controller

  $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();

setters, seem fine

 /**
     * 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;
    }

what var dumps show ( cool )

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 result (not cool )

2014-10-05 12:41:17
and
2014-10-05 12:41:17
oligan
  • 634
  • 6
  • 18

2 Answers2

3

The problem is that you are referencing the same DateTime object you need to clone it.

$date = clone $dateNow;

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

Tom Tom
  • 3,680
  • 5
  • 35
  • 40
2

you cant use the same DateTime Object and expect different results, you need to clone it sth. like:

  $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();  
john Smith
  • 17,409
  • 11
  • 76
  • 117