Skip to content

Instantly share code, notes, and snippets.

@jonbuda
Created August 8, 2012 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonbuda/3295373 to your computer and use it in GitHub Desktop.
Save jonbuda/3295373 to your computer and use it in GitHub Desktop.
Finding a timezone with geonames.org based on geocoordinates
# offset = TimeZoneFinder.gmt_offset(some_lat, some_lng)
# timezone = ActiveSupport::TimeZone[offset]
#
# timezone = TimeZoneFinder.timezoneId(lat, lng)
# Time.zone = timezone
# Time.zone.now
#
class TimeZoneFinder
attr_accessor :result
def self.gmt_offset(lat,lng)
self.new(lat,lng).find('gmtOffset').to_f
end
def self.timezoneId(lat,lng)
self.new(lat,lng).find('timezoneId')
end
def initialize(lat,lng)
uri = URI.parse("http://ws.geonames.org/timezone?lat=#{lat}&lng=#{lng}")
@result = Hash.from_xml(open(uri))
end
def find(key)
result["geonames"]["timezone"][key]
end
end
# Example XML response...
# <geonames>
# <timezone>
# <countryCode>US</countryCode>
# <countryName>United States</countryName>
# <lat>41.8781136</lat>
# <lng>-87.6297982</lng>
# <timezoneId>America/Chicago</timezoneId>
# <dstOffset>-5.0</dstOffset>
# <gmtOffset>-6.0</gmtOffset>
# <rawOffset>-6.0</rawOffset>
# <time>2011-09-01 21:40</time>
# <sunrise>2011-09-02 06:16</sunrise>
# <sunset>2011-09-02 19:22</sunset>
# </timezone>
# </geonames>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment