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.
Map of the world showing time zone regions (2023d), CC BY 4.0 Wikimedia
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 find the timezone information for a location (address or coordinates).
You can test our geocoding API manually on
our demo page.
Caveats
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_nameSee the section of the API documentation describing thetimezoneannotation. -
The
namefield is in the tz database format. Example:Europe/Berlin. - Time zones can and do change regularly, sometimes with very little notice. Governments chage DST rules, political boundaries shift, etc.
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.5432379, 13.4142133
- site of the OpenCage office in Berlin, Germany
var api_key = 'YOUR-API-KEY';
var coords = '52.5432379, 13.4142133'; // 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
Further reading
Happy geocoding!
2,500 geocoding API requests/day - No credit card required