Symfony2 datetime best way to store timestamps?

后端 未结 4 718
醉话见心
醉话见心 2020-12-15 08:55

I don\'t know which is the best way to store a timestamp in the database. I want to store the entire date with hours minutes and seconds but it only stores the date ( for in

4条回答
  •  孤城傲影
    2020-12-15 09:34

    Building on @Pratt's answer I did this. I have 2 fields in my entities one for created and one for modified.

    /**
    * @ORM\Column(type="datetime")
     */
    protected $created_at;
    
    /**
    * @ORM\Column(type="datetime")
     */
    protected $modified_at;
    

    And then using annotation I call this on prePersist and preUpdate

    /**
     * @ORM\PrePersist
     * @ORM\PreUpdate
     */
    public function updatedTimestamps()
    {
        $this->setModifiedAt(new \DateTime(date('Y-m-d H:i:s')));
    
        if($this->getCreatedAt() == null)
        {
            $this->setCreatedAt(new \DateTime(date('Y-m-d H:i:s')));
        }
    }
    

    The function could be broken up into 2 functions one for create one for update, but this is working so I see no reason for the extra code when this is working properly.

提交回复
热议问题