11

I'd like to know the local time where my user is sending his request from. Basically, is there such a thing as a function like this

var localTime = getLocalTime( lat, long );

I'm not sure if a simple division on the lat could work, since most of the countries don't have perfect geometric shapes.

Any help would be great. Any language is accepted. I'd like to avoid calling distant APIs.

Alex
  • 528
  • 1
  • 8
  • 18
  • Well, it involves a remote API, but take a look at the answer to this question. It may give you what you want: http://stackoverflow.com/questions/41504/timezone-lookup-from-latitude-longitude. – Jonathan M Nov 30 '11 at 14:26

5 Answers5

4

The Google Time Zone API seems to be what you're after. It, however does not have any free tier.

The Time Zone API provides time offset data for locations on the surface of the earth. Requesting the time zone information for a specific Latitude/Longitude pair will return the name of that time zone, the time offset from UTC, and the Daylight Savings offset.

vwvw
  • 321
  • 3
  • 12
Josh Hunt
  • 12,949
  • 26
  • 73
  • 96
3

The shapefile used to compute the timezone is not maintained anymore.

I just faced the same issue today, and I am not sure how relevant my answer is after all this time, but I basically just wrote a Python function that does what you want. You can find it here.

https://github.com/cstich/gpstotz

Edit:

As mentioned in the comments I should also post code. The code is based on Eric Muller's shapefile of timezones, which you can get here - http://efele.net/maps/tz/world/.

Edit 2:

As it turns out shapefiles have a somewhat archaic definition of exterior and interior rings (basically exterior rings are using the right hand rule, while interior rings are using the left hand rule). In any case fiona seems to take care of that and I updated the code accordingly.

from rtree import index  # requires libspatialindex-c3.deb
from shapely.geometry import Polygon
from shapely.geometry import Point

import os
import fiona

''' Read the world timezone shapefile '''
tzshpFN = os.path.join(os.path.dirname(__file__),
                   'resources/world/tz_world.shp')

''' Build the geo-index '''
idx = index.Index()
with fiona.open(tzshpFN) as shapes:
    for i, shape in enumerate(shapes):
        assert shape['geometry']['type'] == 'Polygon'
        exterior = shape['geometry']['coordinates'][0]
        interior = shape['geometry']['coordinates'][1:]
        record = shape['properties']['TZID']
        poly = Polygon(exterior, interior)
        idx.insert(i, poly.bounds, obj=(i, record, poly))


def gpsToTimezone(lat, lon):
    '''
    For a pair of lat, lon coordiantes returns the appropriate timezone info.
    If a point is on a timezone boundary, then this point is not within the
    timezone as it is on the boundary. Does not deal with maritime points.
    For a discussion of those see here:
    http://efele.net/maps/tz/world/
    @lat: latitude
    @lon: longitude
    @return: Timezone info string
    '''
    query = [n.object for n in idx.intersection((lon, lat, lon, lat),
                                                objects=True)]
    queryPoint = Point(lon, lat)
    result = [q[1] for q in query
              if q[2].contains(queryPoint)]

    if len(result) > 0:
        return result[0]
    else:
        return None

if __name__ == "__main__":
    ''' Tests '''
    assert gpsToTimezone(0, 0) is None  # In the ocean somewhere
    assert gpsToTimezone(51.50, 0.12) == 'Europe/London'
vwvw
  • 321
  • 3
  • 12
cstich
  • 83
  • 8
  • You should post the relevant code here instead of requiring people to go off-site. Links to other sites can go out-of-date, and cannot be searched by the SO search feature. – Dour High Arch May 25 '15 at 19:50
  • That makes sense, just posted the code. Is there any way to attach files to an answer? – cstich May 26 '15 at 07:32
2

I was searching for the same thing couple of days ago and unfortunately I could not find an API or a simple function that does it. The reason being as you said that countries do not have perfect geometric shapes. You have to create a representation of the area of each time zone and see where your point lies. I think this will be a pain and I have no idea if it can be done at all.

The only one I found is described here: Determine timezone from latitude/longitude without using web services like Geonames.org . Basically you need a database with information about timezones and you are trying to see which one is closest to your point of interest.

However, I was looking for static solutions(without using internet), so if you can use internet connection you can use: http://www.earthtools.org/webservices.htm which provides a webservice to give you the timezone given lat/lon coordinates.

Community
  • 1
  • 1
Petar
  • 2,108
  • 1
  • 22
  • 36
0

As of 2019, Google API does not have any free tier and the data source of @cstich answer is not maintained anymore.

If you want an API, timezonedb.com offers a free tier rate limited to 1 request/second.

The original maintainer of the data used by @cstich link to this project which retrieve data from OpenStreetMap. The readme contains link to look up libraries in a wide variety of languages.

vwvw
  • 321
  • 3
  • 12
-3

Couldn't you simply use the user IP to determine which they live in ? And then you use an array of (Countries | Difference with GMT) to get the local time.

Jeremy67
  • 11
  • 2