Ruby on Rails的:为什么我收到的时区被改写的时候我写了一次到数据库,然后读回来? [英] Ruby on Rails: Why do I get timezones munged when I write a time to the DB, then read it back?
问题描述
我config.time_zone在environment.rb中设置为UTC,而我的MySQL服务器返回当前时间在我的本地时区,当我发出选择现在();在UTC时,我问中选择UTC_TIMESTAMP;
I have config.time_zone in environment.rb set to "UTC", and my mySQL server returns the current time in my local time zone when I issue "select now();" and in utc when I ask for "select utc_timestamp;"
我运行轨道2.1.2,MySQL的宝石2.7.3,ActiveRecord的宝石2.1.2,和MySQL --version返回版本14.12 DISTRIB 5.0.27为Win32(IA32)。
I'm running rails 2.1.2, the mysql gem 2.7.3, activerecord gem 2.1.2, and mysql --version returns "Ver 14.12 Distrib 5.0.27 for Win32 (ia32)".
编辑:我的environment.rb中设置为UTC,并已自从我开始这个项目。重启服务器将回升没有改变。
My environment.rb is set to UTC and had been since I started the project. A server restart would have picked up no changes.
record = Record.find(:first)
puts Time.now
# Tue Nov 25 17:40:48 -0800 2008
record.time_column = Time.now
record.save
mysql> select * from records;
---------------------
2008-11-26 01:40:48
#note that this is the same time, in UTC.
record = Record.find(:first)
puts record.time_column
Wed Nov 26 01:40:48 -0800 2008
#NOTE that this is eight hours in advance!
#All I've done is store a date in the database and retrieve it again!
任何想法是什么原因造成的?
Any ideas what causes this?
推荐答案
我们有关于日期,时区和MySQL同样的问题。后者假定您提供它与它的配置与时区的日期/时间值。
We had the same issue regarding dates, time zones and MySQL. The latter assumes you provide it with date/time values in the timezone it's configured with.
不过,既然你配置的Rails来处理UTC时间,ActiveRecord的在UTC(从而周二11月25日17时40分48秒-0800 2008年成为周三11月26日1时40分48秒0000 2008)之前,将任何日期/时间值使用的SQL更新值/创建查询它生成并发送到MySQL。
But, since you configured Rails to handle time in UTC, ActiveRecord converts any date/time values in UTC (thus Tue Nov 25 17:40:48 -0800 2008 becomes Wed Nov 26 01:40:48 0000 2008) before using the value in the SQL update/create query it generates and sends to MySQL.
在伪code
("time = %t", Tue Nov 25 17:40:48 -0800 2008) => "time = '2008-11-26 01:40:48'
这被认为是2008-11-26一点四十分48秒的 -0800 由MySQL。
看看你的调试日志文件,你就会明白我的意思。它可以正常工作的唯一方法(意为W / O型坏惊喜),是通过设置在同一时区的Rails和MySQL的,这个时区是UTC。这是我们使用的配置。
Look at your debug log file and you'll see what I mean. The only way it can properly work (meaning w/o bad surprises) is by setting the same timezone in Rails AND MySQL, this timezone being UTC. This is the configuration we use.
这篇关于Ruby on Rails的:为什么我收到的时区被改写的时候我写了一次到数据库,然后读回来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!