53

is there any possibility to determine the timezone of point (lat/lon) without using webservices? Geonames.org is not stable enough for me to use :( I need this to work in PHP.

Thanks

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
Jacek Francuz
  • 2,420
  • 8
  • 45
  • 61
  • Geonames have commercial/pay-for services as well as the free service. Have you tried those? – winwaed Apr 07 '11 at 16:52
  • 7
    You could download the geonames db, host it yourself and compare lat/lng to the nearest place (with timezone) in the db? – Adam Hopkinson Apr 07 '11 at 16:55
  • See also: [How to get a time zone from a location?](http://stackoverflow.com/q/16086962/634824) – Matt Johnson-Pint Jun 30 '14 at 17:02
  • Here's a related question with a detailed list of possibilities given: http://stackoverflow.com/questions/16086962/how-to-get-a-time-zone-from-a-location-using-latitude-and-longitude-coordinates/16086964#16086964 – jannikmi Mar 15 '16 at 13:44

17 Answers17

57

I had this problem a while back and did exactly what adam suggested:

  • Download the database of cities from geonames.org
  • convert it to a compact lat/lon -> timezone list
  • use an R-Tree implementation to efficiently lookup the nearest city (or rather, its timezone) to a given coordinate

IIRC it took less than 1 second to populate the R-Tree, and it could then perform thousands of lookups per second (both on a 5 year old PC).

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
  • I've been searching for a solution for a while now and this is awesome. It may not be 100% accurate but it's good enough for what I need. – Micah Jun 06 '11 at 03:59
  • 1
    Sorry if this is not valid, but aren't R-Trees meant for rectangles? I thought that a nearest-neighbor algorithm, such as one using kd-trees was meant for points. – Markos Fragkakis Sep 15 '11 at 20:48
  • 2
    @Markos Fragkakis: Saw your comment just now. The R-Tree library I linked to has a nearest neighbour search. Not sure how exactly it is implemented. But the basic idea should work just as well with a different data structure. – Michael Borgwardt Dec 16 '11 at 19:15
  • Thanks for the last comment! I went for a KD-tree implementation in the end. – Markos Fragkakis Dec 17 '11 at 20:24
  • 17
    I had so much pain to do the part 'convert it to a compact lat/lon -> timezone list' , here it is : https://gist.github.com/1769458. Then i used postgres with postgis, a Gist index on Geography type, and then the query : select timezone_string where ST_DWithin(ST_GeographyFromText('SRID=4326;POINT(2.36 48.86)'), location, 100000, false) order by st_distance(ST_GeographyFromText('SRID=4326;POINT(2.36 48.86)'), location) limit 1. I look 100km around the point I want (2.36 48.86) for decent perfs : 30ms. If it fails, i do 6000km : 1sec :) – Laurent Debricon Feb 08 '12 at 13:36
  • 5
    I created a simple Python scrip to convert GeoNames.org data (and other) to various formats such as MongoDB .json insert scripts for geospatial queries. It can be found here: https://github.com/NuSkooler/GeoToTimeZone – NuSkooler Mar 07 '12 at 04:05
  • 1
    For finding the nearest city to a given coordinate, a quad-tree should be even faster (and simpler). http://en.wikipedia.org/wiki/Quadtree – hennings Apr 25 '12 at 07:40
  • 1
    @hennings: I don't think that would work - the nearest city could be in a completely different branch of the tree. – Michael Borgwardt Apr 25 '12 at 07:59
  • 1
    Isn't this a pretty error-prone solution? For example, Jasper, TN is closest to Chattanooga, TN - and also in a different time zone. It seems like you'd probably get wrong results for most cities on the borders of time zones that aren't the cities listed in the geonames cities list. I know 100% accuracy is pretty impossible, but I'm not sure this is even close. – jep Nov 11 '14 at 23:10
  • @jep: the list is pretty complete. But yes, there will often be wrong results when you've very close to a border. Depends on the application whether that's tolerable. – Michael Borgwardt Nov 12 '14 at 09:39
22

How exact do your results have to be? If a rough estimate is enough, calculate the offset yourself:

offset = direction * longitude * 24 / 360

where direction is 1 for east, -1 for west, and longitude is in (-180,180)

Christian Stade-Schuldt
  • 4,671
  • 7
  • 35
  • 30
  • Thanks really helpful answer, especially if accuracy is not an issue. I also rounded off the decimals in your formula. – KarthikS May 03 '15 at 02:17
  • That's a very rough estimate, only if you're ok having the wrong timezone very often (e.g. the whole Spain/France have a different timezone from London even if they have the same longitude. [Map](https://i.imgur.com/5mcXA7n.jpg)) – fregante Apr 06 '18 at 07:23
  • Why do you have to multiply by `direction`? For longtitude=-90 it gives -6 hours which is fine, no need to multiply by -1. – Anton Bryzgalov Oct 01 '22 at 10:05
  • Equivalent, but easier: offset=longitude/15 – Greg Miller Aug 25 '23 at 03:31
10

I ran into this problem while working on another project and looked into it very deeply. I found all of the existing solutions to be lacking in major ways.

Downloading the GeoNames data and using some spatial index to look up the nearest point is definitely an option, and it will yield the correct result a lot of the time, but it can easily fail if a query point is on the wrong side of a time zone border from the nearest point in the database.

A more accurate method is to use a digital map of the time zones and to write code to find the polygon in that map that contains a given query point. Thankfully, there is an excellent map of the time zones of the world available at http://efele.net/maps/tz/world/ (not maintained anymore). To write an efficient query engine, you need to:

  • Parse the ESRI shapefile format into a useful internal representation.
  • Write point-in-polygon code to test whether a given query point is in a given polygon.
  • Write an efficient spatial index on top of the polygon data so that you don't need to check every polygon to find the containing one.
  • Handle queries that are not contained by any polygon (e.g., in the ocean). In such cases, you should "snap to" the nearest polygon up to a certain distance, and revert to the "natural" time zone (the one determined by longitude alone) in the open ocean. To do this, you will need code to compute the distance between a query point and a line segment of a polygon (this is non-trivial since latitude and longitude are a non-Euclidean coordinate system), and your spatial index will need to be able to return nearby polygons, not just potentially containing polygons.

Each of those are worthy of their own Stack Overflow question/answer page.

After concluding that none of the existing solutions out there met my needs, I wrote my own solution and made it available here:

http://askgeo.com

AskGeo uses a digital map and has a highly optimized spatial index that allows for running more than 10,000 queries per second on my computer in a single thread. And it is thread safe, so even higher throughput is certainly possible. This is a serious piece of code, and it took us a long time to develop, so we are offering it under a commercial license.

It is written in Java, so using it in PHP would involve using:

http://php-java-bridge.sourceforge.net/doc/how_it_works.php

We are also open to porting it for a bounty. For details on the pricing, and for detailed documentation, see http://askgeo.com.

I hope this is useful. It certainly was useful for the project I was working on.

vwvw
  • 372
  • 4
  • 16
James D
  • 1,506
  • 1
  • 17
  • 15
8

I know this is old, but I spent some time looking for this answer. Found something very useful. Google does time zone lookups by long/lat. No free tier anymore :-/

https://developers.google.com/maps/documentation/timezone/

vwvw
  • 372
  • 4
  • 16
Jeff Vdovjak
  • 1,833
  • 16
  • 21
5

You should be able to, if you know the polygon of the timezone to see if a given lat/lon is inside it.

World Time Zone Database enter image description here

Latitude/Longitude Polygon Data enter image description here

SavoryBytes
  • 35,571
  • 4
  • 52
  • 61
5

For areas on land, there are some shapefile maps that have been made for the timezones of the tz (Olson) database. They're not updated quite as regularly as the tz database itself, but it's a great starting point and seems to be very accurate for most purposes.

Tim Parenti
  • 511
  • 7
  • 26
  • 2
    +1 Hi Tim, thank you -- I successfully used these maps in my project with GeoTools to convert from lat/long to time zone IDs, then Joda time to convert instantaneous time plus the time zone IDs to give localised historical times. Sweet. –  Jul 31 '12 at 03:06
4

How about this ?

// ben@jp

function get_nearest_timezone($cur_lat, $cur_long, $country_code = '') {
    $timezone_ids = ($country_code) ? DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, $country_code)
                                    : DateTimeZone::listIdentifiers();

    if($timezone_ids && is_array($timezone_ids) && isset($timezone_ids[0])) {

        $time_zone = '';
        $tz_distance = 0;

        //only one identifier?
        if (count($timezone_ids) == 1) {
            $time_zone = $timezone_ids[0];
        } else {

            foreach($timezone_ids as $timezone_id) {
                $timezone = new DateTimeZone($timezone_id);
                $location = $timezone->getLocation();
                $tz_lat   = $location['latitude'];
                $tz_long  = $location['longitude'];

                $theta    = $cur_long - $tz_long;
                $distance = (sin(deg2rad($cur_lat)) * sin(deg2rad($tz_lat))) 
                + (cos(deg2rad($cur_lat)) * cos(deg2rad($tz_lat)) * cos(deg2rad($theta)));
                $distance = acos($distance);
                $distance = abs(rad2deg($distance));
                // echo '<br />'.$timezone_id.' '.$distance; 

                if (!$time_zone || $tz_distance > $distance) {
                    $time_zone   = $timezone_id;
                    $tz_distance = $distance;
                } 

            }
        }
        return  $time_zone;
    }
    return 'none?';
}
//timezone for one NY co-ordinate
echo get_nearest_timezone(40.772222,-74.164581) ;
// more faster and accurate if you can pass the country code 
echo get_nearest_timezone(40.772222, -74.164581, 'US') ;
j-bin
  • 671
  • 7
  • 9
  • 1
    Can you add some comments which explain how this function works? – codecowboy Oct 16 '13 at 06:46
  • 1
    @codecowboy he's searching the entire list of timezones, each of which specify a *centroid* for the timezone - this isn't reliable, but for lack of better, you might consider this a "best guess" implementation. – mindplay.dk Aug 30 '17 at 13:32
2

I've written a small Java class to do this. It could be easily translated to PHP. The database is embedded in the code itself. It's accurate to 22km.

https://sites.google.com/a/edval.biz/www/mapping-lat-lng-s-to-timezones

The whole code is basically stuff like this:

         if (lng < -139.5) {
          if (lat < 68.5) {
           if (lng < -140.5) {
            return 371;
           } else {
            return 325;
           }

...so I presume a translation to PHP would be easy.

Tim Cooper
  • 10,023
  • 5
  • 61
  • 77
  • Thanks for sharing. THis could be integrated via bash but @flexjack said that they `need this to work in PHP` explicitly. – Alastair Dec 02 '13 at 15:43
  • That would translate into practically any language but having the data in the code is inconvenience for updates and has presumably poor performance, at 30K+ lines. I'd be interested in testing the result, if you update your answer for PHP! :-) – Alastair Dec 06 '13 at 16:00
1

Another solution is to import a table of cities with timezones and then to use the Haversine formula to find the nearest city in that table, relevant to your coordinates. I have posted a full description here: http://sylnsr.blogspot.com/2012/12/find-nearest-location-by-latitude-and.html

For an example of loading the data in MySQL, I have posted an example here (with sources for downloading a small data dump): http://sylnsr.blogspot.com/2012/12/load-timezone-data-by-city-and-country.html

Note that the accuracy of the look-up will be based on how comprehensive your look-up data is.

Credits and References: MySQL Great Circle Distance (Haversine formula)

Community
  • 1
  • 1
Michael M
  • 8,185
  • 2
  • 35
  • 51
1

You can use time zone boundaries, provided here:

http://www.opensource.apple.com/source/TimeZoneData/

1

Not sure if this is useful or not, but I built a database of timezone shapes (for North America only), which is painstakingly accurate and current not just for borders, but also for daylight saving time observance. Also shapes for unofficial exceptions. So you could query the set of shapes for a given location could return multiple shapes that apply to that location, and choose the correct one for the time of year.

You can see an image of the shapes at http://OnTimeZone.com/OnTimeZone_shapes.gif. Blue shapes are around areas that do not observe daylight saving time, magenta shapes those that do observe daylight saving time, and neon green shapes (small and tough to see at that zoom level) are for areas with unofficial deviation from the official time zone. Lots more detail on that available at the OnTimeZone.com site.

The data available for download at OnTimeZone.com is free for non-commercial use. The shape data, which is not available for download, is available for commercial license.

Steve
  • 19
  • 1
1

Unfortunately, time zones are not regular enough for some simple function. See the map in Wikipedia - Time Zone

However, some very rough approximation can be calculated: 1 hour difference corresponds to 15 degrees longitude (360 / 24).

MillKa
  • 413
  • 4
  • 10
0

I downloaded data that matches 5 digit zip codes to time zones, and data that determines the UTC offset for each time zone during DST and non-DST periods.

Then I simplified the data to only consider the first three digits of the ZIP Code, since all ZIP codes that share the first three digits are very close to each other; the three digits identify a unique mail distribution center.

The resulting Json file does require you to decide whether or not you are subject to DST currently, and it probably has some inaccuracy here and there. But it's a pretty good local solution that is very compact and simple to query.

Here it is: https://gist.github.com/benjiwheeler/8aced8dac396c2191cf0

Ben Wheeler
  • 6,788
  • 2
  • 45
  • 55
0

I use geocoder.ca

Input any location in North America, Output geocodes, area codes and timezone in json or jsonp.

For example: http://geocoder.ca/1600%20pennsylvania%20avenue,Washington,DC

Area Code: (202) Time Zone: America/New_York

Json:

{"standard":{"staddress":"Pennsylvania Ave","stnumber":"1600","prov":"DC","city":"WASHINGTON","postal":"20011","confidence":"0.8"},"longt":"-76.972948","TimeZone":"America/New_York","AreaCode":"202","latt":"38.874533"}
Racil Hilan
  • 24,690
  • 13
  • 50
  • 55
Ervin Ruci
  • 829
  • 6
  • 10
0

You can use Google Timezone api. https://maps.googleapis.com/maps/api/timezone/json?location=39.6034810,-119.6822510&timestamp=1331161200&key=YOUR_API_KEY

{
   "dstOffset" : 0,
   "rawOffset" : -28800,
   "status" : "OK",
   "timeZoneId" : "America/Los_Angeles",
   "timeZoneName" : "Pacific Standard Time"
}
jjz
  • 2,007
  • 3
  • 21
  • 30
Sheena Singla
  • 706
  • 7
  • 13
  • Can you explain a bit more? – Dieter Meemken May 17 '16 at 10:33
  • Hi @DieterMeemken , you can use Google Api as mentioned above. In this Google api you have to enter 1.latitude, longitude in location parameter 2. timestamp 3. your api key and it will return you the object containing parameter 'timeZoneId'. – Sheena Singla May 21 '16 at 07:13
  • You can check this link for more info: https://developers.google.com/maps/documentation/timezone/start – jjz Nov 02 '16 at 05:02
0
You can get the timezone based on the location in javascript.

function initAutocomplete() {
        // Create the autocomplete object, restricting the search to geographical
        // location types.
        autocomplete = new google.maps.places.Autocomplete(
                /** @type {!HTMLInputElement} */(document.getElementById('Location')),
                {types: ['geocode']});

        // When the user selects an address from the dropdown, populate the address
        // fields in the form.
        autocomplete.addListener('place_changed', fillInAddress);
    }

    function fillInAddress() {
        // Get the place details from the autocomplete object.
        var place = autocomplete.getPlace();

        fnGettimezone($('#Location').serialize());
        for (var component in componentForm) {
            document.getElementById(component).value = '';
            document.getElementById(component).disabled = false;
        }

        // Get each component of the address from the place details
        // and fill the corresponding field on the form.
        for (var i = 0; i < place.address_components.length; i++) {
            var addressType = place.address_components[i].types[0];
            if (componentForm[addressType]) {
                var val = place.address_components[i][componentForm[addressType]];
                document.getElementById(addressType).value = val;
            }
        }

    }


function fnGettimezone(location) {
    $.ajax({
            url: "http://maps.googleapis.com/maps/api/geocode/json?address=" + location + "&sensor=false",
            dataType: 'json',
            success: function (result) {
                 console.log(result);
                // result is already a parsed javascript object that you could manipulate directly here
                var myObject = JSON.parse(JSON.stringify(result));
                lat = myObject.results[0].geometry.location.lat;
                lng = myObject.results[0].geometry.location.lng;
                console.log(myObject);

                $.ajax({
                    url: "https://maps.googleapis.com/maps/api/timezone/json?location=" + lat + "," + lng + "&timestamp=1331161200&sensor=false",
                    dataType: 'json',
                    success: function (result) {
                        // result is already a parsed javascript object that you could manipulate directly here
                        var myObject = JSON.parse(JSON.stringify(result));
                        $('#timezone').val(myObject.timeZoneName);

                    }
                });

            }
        });
    }
0

This project builds a shapefile from data from OpenStreetMap and link to multiple libraries that handle it. For PHP you can look at https://github.com/minube/geo-timezone

vwvw
  • 372
  • 4
  • 16