php - Symfony2 datetime 存储时间戳的最佳方式?

标签 php datetime symfony doctrine-orm timestamp

我不知道哪种是在数据库中存储时间戳的最佳方法。我想存储包含小时、分钟和秒的整个日期,但它只存储日期(例如 2012-07-14 ),我想存储 2012-07-14 HH:MM:SS。我正在使用 dateTime 对象。这是代码:

在 Controller 中:

$user->setCreated(new \DateTime());

在实体中:

/**
 * @var date $created
 *
 * @ORM\Column(name="created", type="date")
 */
private $created;

将日期和时间分别存储在数据库中是否更好?或者更好地像 YYYY-MM-DD HH:MM:SS 一样存储在一起?然后我将比较日期并计算剩余时间,因此这对于简化以后的操作很重要。所以你怎么看 ?有人可以帮助我吗?

最佳答案

在数据库中存储时间戳的最佳方法显然是使用时间戳列(如果您的数据库支持该类型)。而且由于您可以将该列设置为在创建时自动更新,因此您甚至不必为其提供 setter 。

有一个Timestampable behavior extension for Doctrine 2从用户态方面来说,它也确实做到了这一点:

Timestampable behavior will automate the update of date fields on your Entities or Documents. It works through annotations and can update fields on creation, update or even on specific property value change.

Features:

  • Automatic predifined date field update on creation, update and even on record property changes
  • ORM and ODM support using same listener
  • Specific annotations for properties, and no interface required
  • Can react to specific property or relation changes to specific value
  • Can be nested with other behaviors
  • Annotation, Yaml and Xml mapping support for extensions

有了这种行为,您所需要做的就是将注释更改为

/**
 * @var datetime $created
 *
 * @Gedmo\Timestampable(on="create")
 * @ORM\Column(type="datetime")
 */
private $created;

那么您不需要在代码中调用setCreated。该字段将在第一次创建实体时自动设置。

关于php - Symfony2 datetime 存储时间戳的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11504997/

相关文章:

php - 如何打开位于本地c盘的pdf文件

mysql - 如果当前时间在行的开始时间和结束时间之间,则检索行

symfony - 如何禁用 symfony2 中某些路由的监听器?

php -/etc/cron.d 中的作业不适用于 ubuntu

php - laravel Collections 函数仅适用于 Eloquent ORM 结果总是返回空集合

python - Pandas :在特定时间窗口中选择行

forms - 模板渲染过程中抛出异常一个表单只能提交一次

php - 如何在 Symfony 3 中创建将显示在标题中每个子页面上的表单

php - 如何检查 php 中是否存在键/值对?

datetime - 如何获取 Alexa 技能的用户日期/时间或时区信息?