Reputation: 2666
In my application I save data with doctrine to an mysql database. for me it is totally sufficient to save the date and not also the time therefore I have chosen the Date format for my database field.
In the entity of my Symfony 4 app this looks like that:
/**
* @var DateTime
*
* @ORM\Column(name="create_date", type="date", nullable=false, options={"default" = "CURRENT_TIMESTAMP"})
* @Assert\NotBlank
*/
private $createDate;
/**
* @param DateTime $createDate
*
* @return Asset
*/
public function setCreateDate(DateTime $createDate)
{
$this->createDate = $createDate;
return $this;
}
The resulting SQL statement looks as follows:
INSERT INTO asset
(name, create_date, beide, comment, amount, user_id, category_id)
VALUES
("Schmeckerlis","2019-01-19 16:03:53",0,"",7.34,345,345)
As you see there is the time added. Is this how you set up a date field with doctrine?
Do I have to change it to a DateTime or Timestamp field?
Should I remove the default value in the entity?
https://www.doctrine-project.org/projects/doctrine-dbal/en/2.6/reference/types.html#date says the following:
"date: Maps and converts date data without time and timezone information. If you know that the data to be stored always only needs to be a date without time and timezone information, you should consider using this type. Values retrieved from the database are always converted to PHP's \DateTime object or null if no data is present."
Upvotes: 1
Views: 6005
Reputation: 1654
CURRENT_TIMESTAMP
returns the date and time as YYYY-MM-DD HH-MM-SS
. If I understand you correctly you only need the YYYY-MM-DD
part.
For this you have to remove the options={"default" = "CURRENT_TIMESTAMP"}
and do this in the constructor method of the entity. This one gets called everytime you do new Entity()
.
public function __construct()
{
$date = new \DateTime();
$this->createDate = $date->format('Y-m-d');
}
Upvotes: 2