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

查看:596
本文介绍了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
 *
 * @ORM\Column(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?

推荐答案

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

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映射支持扩展名

  • 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

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

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

/**
 * @var datetime $created
 *
 * @Gedmo\Timestampable(on="create")
 * @ORM\Column(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天全站免登陆