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

Answers


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

Need Your Help

NSString is being truncated

ios soap nsstring truncate string-length

In my app I am using a webservice that sign a document. I have to send the documento in base64format inside the SOAP call. The problem is that when I try to send a big document like a 11mb one, the

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.