如何在symphony 3中设置日期时间字段以进行更新或插入数据?

fli*_*lik 4 php symfony

我试图以这种方式在symfony 3.4中设置日期和时间字段:

$eventProject = new $eventProject();

$eventProject->setDateFrom('2018-05-09');
Run Code Online (Sandbox Code Playgroud)

当我保存值时,它给我的错误如下:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'dateFrom' can
  not be null
In ConversionException.php line 95:

  Could not convert PHP value '2018-05-09' of type 'string' to type 'datetime
  '. Expected one of the following types: null, DateTime
Run Code Online (Sandbox Code Playgroud)

我无法理解什么是错的?

hco*_*oat 7

您需要使用PHP的DateTime对象来设置日期.

$eventProject = new $eventProject();
$date = new \DateTime('2018-05-09');
$eventProject->setDateFrom($date);
Run Code Online (Sandbox Code Playgroud)

这也意味着您必须DateTime在检索日期时使用.

$date = $eventProject->getDate();
var_dump($date->format("Y-m-d")); 
//string(10) "2018-05-09"
Run Code Online (Sandbox Code Playgroud)

当您想要将日期作为字符串时,请务必format在检索到的DateTime对象上使用.

这更多的是关于如何eventProject编写类/实体而不是强制使用的东西Symfony.据说这是在PHP项目中与时间一起工作的一种常见方式.一开始它看起来有点尴尬,但随着你习惯了,你会发现DateTime它非常方便.