How to get TimeZone by RemoteIP or for specific city

The goal: to find out the TimeZone of a visitor.

There are few free services that can give you this information.

First step is to get the City name by RemoteIP address – there are free services/databases that helps you to achieve this, one of them is MaxMind.

When you have a city name you can get its latitude/longitude from the database of the same service or you can use Google API like this:

For Berlin, Germany:
http://maps.googleapis.com/maps/api/geocode/json?address=Berlin&sensor=false

You will get JSON result like this:

{
  "results" : [
  {
    "address_components" : [
    {
      "long_name" : "Berlin",
      "short_name" : "Berlin",
      "types" : [ "locality", "political" ]
    },
    {
      "long_name" : "Berlin",
      "short_name" : "Berlin",
      "types" : [ "administrative_area_level_1", "political" ]
    },
    {
      "long_name" : "Germany",
      "short_name" : "DE",
      "types" : [ "country", "political" ]
    }
    ],
    "formatted_address" : "Berlin, Germany",
      "geometry" :
      {
        "bounds" :
        {
          "northeast" :
          {
            "lat" : 52.6754542,
            "lng" : 13.7611176
          },
          "southwest" :
          {
            "lat" : 52.33962959999999,
            "lng" : 13.0911663
          }
        },
        "location" :
        {
          "lat" : 52.52000659999999,
          "lng" : 13.404954
        },
        "location_type" : "APPROXIMATE",
        "viewport" :
        {
           "northeast" :
           {
             "lat" : 52.6754542,
             "lng" : 13.7611176
           },
           "southwest" :
           {
             "lat" : 52.33962959999999,
             "lng" : 13.0911663
           }
         }
       },
       "types" : [ "locality", "political" ]
     }
   ],
   "status" : "OK"
}

After getting latitude and longitude of the city you can now ask Google for the TimeZone like this
https://maps.googleapis.com/maps/api/timezone/json?location=52.6754542,13.7611176&timestamp=1331161200&sensor=false

Note: timestamp is number of seconds since Jan 1st, 1970 which you can calculate in csharp (C#) using these function:

public static double ConvertToUnixTimestamp(DateTime date)
{
  DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
  TimeSpan diff = date.ToUniversalTime() - origin;
  return Math.Floor(diff.TotalSeconds);
}

public static DateTime ConvertFromUnixTimestamp(double timestamp)
{
 DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
 return origin.AddSeconds(timestamp);
}

And it will return this JSON result with TimeZone offset and name

{
  "dstOffset": 0,
  "rawOffset": 3600,
  "status": "OK",
  "timeZoneId": "Europe/Berlin",
  "timeZoneName": "Central European Standard Time"
}
Follow

Get every new post delivered to your Inbox

Join other followers