Symfony2 datetime 存储时间戳的最佳方式? [英] Symfony2 datetime best way to store timestamps?

查看:17
本文介绍了Symfony2 datetime 存储时间戳的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道在数据库中存储时间戳的最佳方式是什么.我想用小时分和秒存储整个日期,但它只存储日期(例如 2012-07-14 ),我想存储 2012-07-14 HH:MM:SS.我正在使用 dateTime 对象.代码如下:

I don't know which is the best way to store a timestamp in the database. I want to store the entire date with hours minutes and seconds but it only stores the date ( for instance 2012-07-14 ) and i want to store 2012-07-14 HH:MM:SS. I am using the dateTime object. Here is the code:

在控制器中:

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

在实体中:

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

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

Is it better to store the date and the the time separately in the database ? or better to store all together like YYYY-MM-DD HH:MM:SS ? I will have then to compare dates and calculate the remaining times, so that is important in order to simplify the operations later. So what do you think ? can somebody help me?

推荐答案

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

The best way to store a timestamp in the database is obviously to use the timestamp column if your database supports that type. And since you can set that column to autoupdate on create, you dont even have to provide a setter for it.

有一个 适用于 Doctrine 2 的时间戳行为扩展用户端也一样:

There is a Timestampable behavior extension for Doctrine 2 which does exactly that from the userland side as well:

时间戳行为将自动更新您的实体或文档上的日期字段.它通过注释工作,可以在创建、更新甚至特定属性值更改时更新字段.

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.

特点:

  • 在创建、更新甚至记录属性更改时自动更新预定义日期字段
  • ORM 和 ODM 支持使用相同的侦听器
  • 属性的特定注释,不需要接口
  • 可以对特定属性或特定值的关系变化做出反应
  • 可以与其他行为嵌套
  • 对扩展的注释、Yaml 和 Xml 映射支持

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

With this behavior, all you need to do is change your annotation to

/**
 * @var datetime $created
 *
 * @GedmoTimestampable(on="create")
 * @ORMColumn(type="datetime")
 */
private $created;

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

Then you dont need to call setCreated in your code. The field will be set automatically when the Entity is created for the first time.

这篇关于Symfony2 datetime 存储时间戳的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆