Ruby on Rails和Active Record独立脚本对于数据库值不同意:时间戳 [英] Ruby on Rails and Active Record standalone scripts disagree on database values for :timestamps

查看:74
本文介绍了Ruby on Rails和Active Record独立脚本对于数据库值不同意:时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天早些时候发布了一个问题,当时我在这个问题上还没有归零。我可以在这里更简洁。

I posted a question earlier today when I'd not zeroed in quite so far on the problem. I'll be able to be more concise here.

我在Windows上运行RoR 2.1.2,使用MySQL。 SQL Server的本机时区是UTC。我的当地时区是太平洋(-0800)

I'm running RoR 2.1.2, on Windows, with MySQL. The SQL server's native time zone is UTC. My local timezone is Pacific (-0800)

我有一个模型,带有:timestamp类型列,我可以使用以下操作:

I have a model with a :timestamp type column which I can do things like this with:

record = Record.find(:first)
record.the_time = Time.now()

当我在数据库中执行select * from records时,显示的时间是我当地时间提前八小时,这是正确的,给出数据库是在UTC。 (我已经通过一个简单的'select now()'和'select utc_timestamp()''来验证它是'utc'')

When I do a "select * from records" in the database, the time shown is eight hours in advance of my local time, which is correct, given that the DB is on UTC. (I have verified that it is 'thinking in utc' with a simple 'select now()' and 'select utc_timestamp()')

这是麻烦开始的地方。如果我在视图中显示时间:

This is where the trouble begins. If I display the time in a view:

<%= h record.the_time %>

...然后我得到正确的时间,以UTC格式显示。如果我在当地时间16:40:00写信给数据库,数据库显示为00:40:00。

...then I get back the correct time, displayed in UTC format. If I wrote to the database at 16:40:00 local time, the database showed 00:40:00.

但是,如果我正在运行独立脚本:

HOWEVER, if I am running a standalone script:

record = Record.find(:first)
puts record.the_time

...然后我得到我在数据库中存储的UTC时间(00:40:00),但是使用本地时区:

...then I get back the UTC time that I stored in the database (00:40:00,) but with the local timezone:

Wed Nov 26 00:40:00 (-0800) 2008

...八小时的时间扭曲。为什么存储时间正确翻译,但是检索它不是?如果我比较DB中最近的存储时间,并将其与当前时间进行比较,则当前时间较少,这不仅仅是字符串转换问题。

...an eight-hour time warp. Why is it that storing the time translates it correctly, but retrieving it does not? If I compare a stored time from the recent past in the DB and compare it to the current time, the current time is less - telling me this isn't just a string conversion issue.

任何想法?

推荐答案

通过将时间存储为整数(Time.now()。to_i())并将其转换回我需要显示的时间(Time.at(the_time_the_database_returned_to_me))),这样做更容易。)这几乎不是最好的解决方案,但这是唯一有效的。

In the end, it was far easier to do this by storing times as an integer (Time.now().to_i()) and converting them back to a time when I needed to display them (Time.at(the_time_the_database_returned_to_me).) This is hardly the best solution, but it was the only one that worked.

这篇关于Ruby on Rails和Active Record独立脚本对于数据库值不同意:时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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