【问题标题】:Symfony 4 - Set DateTimeSymfony 4 - 设置日期时间
【发布时间】:2018-11-01 04:44:50
【问题描述】:

所以我一直在关注这个数据库和教义教程:https://symfony.com/doc/current/doctrine.html

唯一的区别是我在其中添加了一个 created_ts 字段(在其他一些字段中,但它们工作正常,因此无需进入它们)。

我使用make:entity 命令生成我的类,设置我的created_ts 的方法生成如下:

public function setCreatedTs(\DateTimeInterface $created_ts): self
{
    $this->created_ts = $created_ts;

    return $this;
}

所以在我的/index 页面中,我使用以下方法保存了一个新实体:

$category->setCreatedTs(\DateTimeInterface::class, $date);

我有一种有趣的感觉,这会出错,我是对的:

Type error: Argument 1 passed to App\Entity\Category::setCreatedTs() must implement interface DateTimeInterface, string given

但我不确定如何在函数中实现DateTimeInterface。我尝试使用谷歌搜索,但它显示了很多Symfony2 帖子,我尝试了一些无济于事。

如何通过->set 方法在我的实体中设置datetime 值?

(如果已经有答案,请链接。#symfonyScrub)

更新

# tried doing this:
$dateImmutable = \DateTime::createFromFormat('Y-m-d H:i:s', strtotime('now')); # also tried using \DateTimeImmutable

$category->setCategoryName('PHP');
$category->setCategoryBio('This is a category for PHP');
$category->setApproved(1);
$category->setGuruId(1);
$category->setCreatedTs($dateImmutable); # changes error from about a string to bool

【问题讨论】:

    标签: symfony datetime symfony4


    【解决方案1】:

    如果您的日期是当前日期,您可以这样做:

    $category->setCreatedTs(new \DateTime())
    

    您的第一个错误是由返回时间戳的 strtotime 函数引起的,但 \DateTime 构造函数需要 Y-m-d H:i:s 格式。

    这就是为什么它没有创建有效的 \DateTime,而是返回 false。

    即使在这种情况下没有必要,您也应该这样做以根据时间戳创建 \DateTime

    $date = new \DateTime('@'.strtotime('now'));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多