The problem
You have addresses or geographic coordinates (longitude and latitude)
and you want to know which time zone the location belongs to.
Overview
Humans have divided the world into time zones for the purposes of local time keeping. These zones typically follow cultural or political boundaries rather than logical boundaries. Time zone boundaries can change over time. Observation of Daylight Savings Time also varies widely.
As a result of this complexity converting addresses and/or geocoordinates (longitude, latitude) into time zone is a common task for software developers.
You can use the OpenCage geocoding API to geocode addresses or coordinates find the timezone information for a location.
You can test our geocoding API manually on our demo page.
Caveats / Points to Note
There are a few points you should note when working with the time zone
information returned by the OpenCage geocoding API.
-
We return five different bits of information about the time zone:
name, now_in_dst, offset_sec, offset_string, short_name
-
The
name
field is in the tz database format. Example:Europe/Berlin
- Time zones can and do change, sometimes with very little notice.
Code Example
Here's a small example of making a geocoding request to the
OpenCage API in javascript to determine the time zone of the
coordinates
52.3877830, 9.7334394
- site of the OpenCage office in Hannover, Germany.
We also have
libraries for over 30 other programming languages.
including languages commonly used in research like python, R, stata,
matlab, and many others.
<script>
var api_key = 'YOUR-API-KEY';
var coords = '52.3877830, 9.7334394'; // lat,lng
var api_url = 'https://api.opencagedata.com/geocode/v1/json'
var request_url = api_url
+ '?'
+ 'key=' + api_key
+ '&q=' + encodeURIComponent(coords)
+ '&pretty=1';
// see full list of required and optional parameters:
// https://opencagedata.com/api#forward
var request = new XMLHttpRequest();
request.open('GET', request_url, true);
request.onload = function() {
// see full list of possible response codes:
// https://opencagedata.com/api#codes
var data = JSON.parse(request.responseText);
if (request.status === 200){ // Success!
// see details of timezone response
// https://opencagedata.com/api#timezone
var tz = 'no time zone data returned';
if (data.results[0].annotations.timezone.name != null){
tz = data.results[0].annotations.timezone.name;
}
console.log('timezone: ' + tz);
} else {
console.log("unable to geocode! Response code: " + request.status);
console.log('error msg: ' + data.status.message);
}
};
request.onerror = function() {
// There was a connection error of some sort
console.log("unable to connect to server");
};
request.send(); // make the request
</script>
Further Reading
Happy geocoding!
whichever time zone you happen to be in