简体   繁体   中英

Rails time zone from offset and dst

I am looking for some help in how I can store the correct timezone in Rails, from data that provides me with a UTC offset, and DST.

The data comes from http://openflights.org/data.html

Timezone Hours offset from UTC. Fractional hours are expressed as decimals, eg. India is 5.5.

DST Daylight savings time. One of E (Europe), A (US/Canada), S (South America), O (Australia), Z (New Zealand), N (None) or U (Unknown).

I am wondering how I could use this data in Rails to store the timezone of these airports as a string in a Timezone column that Rails would recognise.

I needed the same functionality in the slightly simpler case of a database of USA zipcodes which includes a UTC hours offset and Y/N field indicating if it participates in daylight savings time, so West coast USA zipcodes in this database all have "-8" and "Y".

I could not find a built-in Rails method to do it, so I manually created a lookup hash where the key is the UTC & DST fields catenated, eg, "#{utc}#{dst}" and the value is the timezone name. This method could work for utc offsets such as "5.5" as well.

In the method that does the lookup is given the utc and dst values, I specify a default timezone (USA west coast for example) in the case where the hash lookup returns nil because an unexpected value such as "-5N" (since the east coast does not have any non-DST states that should never occur).

But the same method could be applied globally by creating a hash that represented all the possible timezone with both Y and N values for daylight savings time.

class MyZip

HOUR_DST_TO_TIMEZONE_NAME = {
  "-5Y" => "Eastern Time (US & Canada)",
  "-6Y" => "Central Time (US & Canada)",
  "-7Y" => "Mountain Time (US & Canada)",
  "-7N" => "Arizona",
  "-8Y" => "Pacific Time (US & Canada)",
  "-9Y" => "Alaska",
  "-10N" => "Hawaii"
  }

def self.timezone_name_from_zip_hour_dst(utc, dst)
  key = "#{utc}#{dst}" 
  return HOUR_DST_TO_TIMEZONE_NAME[key] || MyZip.unknown_timezone_name
end
...

I don't think there there is a solution for this, unless you create a custom mapping of the DST and offset to a particular timezone.

I ended up using the geonames.org webservice, to find out the timezone based on latitude/longitude.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM