简体   繁体   中英

Rails TZInfo::Timezone help

I use Rails TZInfo::Timezone

How could i add new city in this.

For example : I want to show 'Washington, DC' time zone my application,but there is no mapping available for that city.

I retrieve all timezones using TZInfo::Timezone.get() method

Please give some expert suggestion.

This is a little involved, but you could use geocoder to get the latitude and longitude of the city, then use that to get the time zone from geonames.org. Here's an example in Ruby:

search_location = 'Washington, DC'

geocoder_results = Geocoder.search(search_location)
# This assumes the city name will always get results from geocoder
nearest_lat = geocoder_results[0].latitude
nearest_lon = geocoder_results[0].longitude

resp = Net::HTTP.get_response(URI.parse('http://api.geonames.org/timezoneJSON?lat=' + nearest_lat.to_s + '&lng=' + nearest_lon.to_s + '&username=your_user_name_here'))
geonames_tz_info = JSON.parse(resp.body)
city_time_zone = geonames_tz_info['timezoneId']

time_zone = TZInfo::Timezone.get(city_time_zone)

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