【问题标题】:How can I store a date into my database via formbuilder?如何通过 formbuilder 将日期存储到我的数据库中?
【发布时间】:2019-09-25 10:08:52
【问题描述】:

我尝试在我的数据库中存储一个日期:

$entity->setTimestamp(\DateTime::createFromFormat('d.m.Y', "2005-08-15T15:52:01+00:00"));

但我收到错误消息:

传递给 App\Entity\Documents::setTimestamp() 的参数 1 必须 实现接口 DateTimeInterface,给定布尔值,

我的实体中的功能:

  public function setTimestamp(\DateTimeInterface $timestamp): self {
    $this->timestamp = $timestamp;
    return $this;
  }

【问题讨论】:

  • \DateTime::createFromFormat() 失败时返回布尔值 FALSE。您的格式字符串与日期字符串不匹配。 php.net/manual/en/datetime.createfromformat.php
  • 正确答案是$entity->setTimestamp(\DateTime::createFromFormat('d.m.Y', "15.08.2005"));

标签: php symfony datetime doctrine entity


【解决方案1】:

您的格式和日期时间不正确。使用以下代码

$date_time = DateTime::createFromFormat('Y-m-d\TH:i:sP', "2005-08-15T15:52:01+00:00");
$entity->setTimestamp($date_time->format("d.m.Y"));

这也是简单的字符串。因此,请更改您的 setTimestamp 函数。否则你可以返回整个$date_time

【讨论】:

  • 使用 Symfony / Doctrine 设置日期对象的日期,并让 Doctrine 处理转换为数据库值
  • 现在错误是App\Entity\Documents::setTimestamp() must implement interface DateTimeInterface, string given,
  • 正确答案是 $entity->setTimestamp(\DateTime::createFromFormat('d.m.Y', "15.08.2005"));
  • 是的,你是对的。但是如果用户不想改变格式怎么办?如果你想要 DateTime 接口,你仍然可以使用$date_time
猜你喜欢
  • 1970-01-01
  • 2019-12-19
  • 2017-11-04
  • 1970-01-01
  • 2019-04-01
  • 1970-01-01
  • 2011-01-27
  • 1970-01-01
  • 2018-02-02
相关资源
最近更新 更多