开发者

Preserving timezones in Rails

If I have a time string of the form "Wed, 22 Jun 2011 09:43:58 +0200" coming from a client, I wish to store it with the time zone preserved. This is important because it's not just the absolute UTC time that is important but also the timezone.

Time.zone.pa开发者_运维问答rse(t) will convert the time to whatever the zone that Time.zone is using at the time, losing the source timezone.

Do I have to manually extract the timezone from the above string or is there an idiomatic way to do this?


A DateTime field can only store 'YYYY-MM-DD HH:MM:SS' (MySQL), no Time Zone info.

You should store the datetime in UTC, and the Timezone in a different field, preferably as an integer specifying the offset from UTC in minutes.

You can extract the offset like this:

ruby-1.9.2-p180:001:0>> require 'active_support/all' # included by Rails by default
# => true
ruby-1.9.2-p180:002:0>> dt = DateTime.parse "Wed, 22 Jun 2011 09:43:58 +0200"
# => Wed, 22 Jun 2011 09:43:58 +0200
ruby-1.9.2-p180:003:0>> dt.utc_offset
# => 7200
ruby-1.9.2-p180:004:0>> dt.utc
# => Wed, 22 Jun 2011 07:43:58 +0000

EDIT:

And to round trip the excercise

ruby-1.9.2-p180 :039 > u.utc.new_offset(u.offset)
=> Wed, 22 Jun 2011 09:43:58 +0500 
ruby-1.9.2-p180 :040 > u
=> Wed, 22 Jun 2011 09:43:58 +0500 


I think you are looking for the following solution:

In ApplicationController:

before_filter :get_tz

def get_tz
  @tz = current_user.time_zone
end

def use_tz
  Time.use_zone @tz do
    yield
  end
end

And in a controller add around filter at the beginnig

around_filter :use_tz
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜