Preserving timezones in Rails

2019-03-31 22:32发布

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.parse(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?

2条回答
冷血范
2楼-- · 2019-03-31 22:55

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
查看更多
Explosion°爆炸
3楼-- · 2019-03-31 23:01

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 
查看更多
登录 后发表回答