4

I'm running in Rails 3.2 and I can't figure out a nice way to parse a time that's given to me in an arbitrary time zone.

As an example this is the format I'm given in separate keys

{
  "start_date"=>"2013-04-24 13:00:00",
  "timezone"=>"America/Los_Angeles",
  "timezone_offset"=>"GMT-0700",
  ...
}

This question comes very close to answering it with:

time = ActiveSupport::TimeZone.new('UTC').parse('2010-02-05 01:00:01')

The problem is when I put in "America/Los_Angeles" as an argumento to Timezone.new, it spits out a timezone of GMT-8, I think due to DST changing. On the other hand, the data I receive defines the timezone offset from GMT. So for my example, the desired output is a timezone of GMT-7.

Is there any way to get the timezone if I know the gmt offset, instead of using the name of the timezone?

Community
  • 1
  • 1
Tal
  • 1,298
  • 2
  • 10
  • 20

1 Answers1

4

You can use [] on ActiveSupport::Timezone, passing the gmt offset in hours as the argument.

As seen on api.rubyonrails.org:

[](arg)

Locate a specific time zone object. If the argument is a string, it is interpreted to mean the name of the timezone to locate. If it is a numeric value it is either the hour offset, or the second offset, of the timezone to find. (The first one with that offset will be returned.) Returns nil if no such time zone is known to the system.

Code example:

ActiveSupport::TimeZone["America/Los_Angeles"]                              
 => (GMT-08:00) America/Los_Angeles
ActiveSupport::TimeZone[-8]                              
 => (GMT-08:00) America/Los_Angeles

So, what you would do is:

time = ActiveSupport::TimeZone[-7].parse('2013-04-24 13:00:00')

However, be careful since an offset may be equivalent to more than one timezone, since many timezones can be on the same offset.

Cezar
  • 55,636
  • 19
  • 86
  • 87
  • 1
    Awesome, thanks, I knew it took strings, didn't know it also took offset times. – Tal Mar 19 '13 at 19:44