简体   繁体   English

Rails 3.2 + Ruby 1.9.3,created_at以错误的时区返回

[英]Rails 3.2 + Ruby 1.9.3, created_at returns with wrong timezone

I upgraded to Rails 3.2 and Ruby 1.9.3 and I get a very strange behavior 我升级到Rails 3.2和Ruby 1.9.3,我得到了一个非常奇怪的行为

I have a Model called Entry. 我有一个名为Entry的模型。 when a new Entry is created it get inserted into the DB with the current date and time. 创建新条目时,它将以当前日期和时间插入到DB中。

But when I run Entry.find_by_id(THE_ENTRY_ID).created_at I get the "correct" created at datetime but In a different TimeZone for example: in the db: 但是当我运行Entry.find_by_id(THE_ENTRY_ID).created_at我得到了在datetime创建的“正确”但在另一个TimeZone中,例如:在db中:

2013-03-24 00:05:29 2013-03-24 00:05:29

while in the Rails console and in the application: 而在Rails控制台和应用程序中:

Sat, 23 Mar 2013 20:05:29 EDT -04:00 2013年3月23日星期六20:05:29 EDT -04:00

Why is it suddenly returning the wrong time zone? 为什么突然回到错误的时区?

OK after reading the DOCS and seeing this rails casts: http://railscasts.com/episodes/106-time-zones-revised 读完DOCS并看到这个导演后,确定: http//railscasts.com/episodes/106-time-zones-revised

everything is now clear. 一切都清楚了。

config.time_zone = 'Eastern Time (US & Canada)'

this setting is the actual setting that's in charged of converting all time objects to this current time zone. 此设置是将所有时间对象转换为当前时区的实际设置。 that is way i saw it as -4 这就是我把它看作-4的方式

this setting: 此设置:

config.active_record.default_timezone

is the one that decides on how to save the time in the DB, but... it only gets 2 possible values: :local and :UTC and the default is :UTC 是决定如何在DB中节省时间的那个,但是...它只获得2个可能的值:: local和:UTC,默认值为:UTC

when i used the rails console to see my entry the time presented is after the conversion to 'Eastern Time' , in order to see the actual date stored in the DB use: 当我使用rails控制台查看我的条目时,显示的时间是在转换为“东部时间”之后,为了查看存储在数据库中的实际日期使用:

created_at_before_type_cast

which returned the UTC time as it is the default 返回UTC时间,因为它是默认值

and the reason i thought that in the DB its stored in my time zone +2 is because i used MySQL Workbench and its GUI just showed me the datetime values in my local machine time. 我认为在DB中存储在我的时区+2中的原因是因为我使用了MySQL Workbench,它的GUI只显示了我当地机器时间的日期时间值。

summary: 摘要:

the setting that actually matters: 实际上重要的设置:

config.time_zone

it works just fine. 它工作得很好。 going through the DOCS is important 通过DOCS非常重要

Check the configuration in the application.rb . 检查application.rb的配置。 If no timezone is set, rails will take the default timezone of your operating system. 如果未设置时区,则rails将采用操作系统的默认时区。 To fix that, set UTC as the timezone. 要解决此问题,请将UTC设置为时区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM