日期时间的红宝石毫秒的分辨率 [英] Millisecond resolution of DateTime in Ruby

查看:240
本文介绍了日期时间的红宝石毫秒的分辨率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个字符串 2012-01-01T01:02:03.456 ,我使用的ActiveRecord存储在Postgres数据库TIMESTAMP

I have a string like 2012-01-01T01:02:03.456 that I am storing in a Postgres database TIMESTAMP using ActiveRecord.

不幸的是,红宝石似乎砍掉毫秒:

Unfortunately, Ruby seems to chop off the milliseconds:

ruby-1.9.3-rc1 :078 > '2012-12-31T01:01:01.232323+3'.to_datetime
 => Mon, 31 Dec 2012 01:01:01 +0300 

Postgrs支持微秒分辨率。我怎样才能让我的时间戳进行相应的保存?我至少需要毫秒。

Postgrs supports microsecond resolution. How can I get my timestamp to be saved accordingly? I need at least millisecond resolution.

(PS是的,我可以砍在Postgres的毫秒整数列;那种失败的ActiveRecord的全部目的的)

(PS Yes I could hack in a milliseconds integer column in postgres; that kind of defeats the whole purpose of ActiveRecord.)

更新:
非常有帮助的答复显示,Ruby的的DateTime 终止的不是的斩去毫秒;使用 #to_f 显示它。但是,这样做的:

UPDATE:
The very helpful responses showed that Ruby's DateTime is not chopping off milliseconds; using #to_f shows it. But, doing:

m.happened_at = '2012-01-01T00:00:00.32323'.to_datetime
m.save!
m.reload
m.happened_at.to_f

是否丢弃毫秒。

Does drop the milliseconds.

现在,有趣的是, created_at 显示出来毫秒,无论是在Rails和Postgres的。但是其他的时间戳字段(如 happened_at 以上)没有。 (也许Rails使用一个 NOW()功能 created_at ,而不是传递一个日期时间)。

Now, the interesting thing is that created_at does show milliseconds, both in Rails and Postgres. But other timestamps fields (like happened_at above) don't. (Perhaps Rails uses a NOW() function for created_at as opposed to passing in a DateTime).

这导致了我的终极问题:
我怎样才能获得的ActiveRecord为preserve毫秒级的时间戳字段?

Which leads to my ultimate question:
How can I get ActiveRecord to preserve millisecond resolution on timestamp fields?

推荐答案

修改 m.happened_at ='2012-01-01T00:00:00.3​​2323'.to_datetime 的code以上 m.happened_at ='2012-01-01T00:00:00.3​​2323'。解决了这个问题,但我不知道为什么

Changing m.happened_at = '2012-01-01T00:00:00.32323'.to_datetime in the code above to m.happened_at = '2012-01-01T00:00:00.32323' solves the problem, though I have no idea why.

这篇关于日期时间的红宝石毫秒的分辨率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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