给定一个位置的经度和纬度,如何知道该位置的有效时区?
在大多数情况下,我们正在寻找IANA/Olson时区id,尽管有些服务可能只返回UTC偏移量或其他一些时区标识符。详细信息请阅读时区标签信息。
给定一个位置的经度和纬度,如何知道该位置的有效时区?
在大多数情况下,我们正在寻找IANA/Olson时区id,尽管有些服务可能只返回UTC偏移量或其他一些时区标识符。详细信息请阅读时区标签信息。
当前回答
It's indeed important to recognize that this a more complicated problem than most would suspect. In practice many of us are also willing to accept a working set of code that works for "as many cases as possible", where at least its fatal issues can be identified and minimized collectively. So I post this with all of that and the spirit of the OP in mind. Finally, for practical value to others who are trying to convert GPS to timezone with the end goal of having a location-sensitive time object (and more importantly to help advance the quality of average implementations with time objects that follow from this wiki) here is what I generated in Python (please feel free to edit):
import pytz
from datetime import datetime
from tzwhere import tzwhere
def timezoned_unixtime(latitude, longitude, dt):
tzw = tzwhere.tzwhere()
timezone_str = tzw.tzNameAt(latitude, longitude)
timezone = pytz.timezone(timezone_str)
timezone_aware_datetime = timezone.localize(dt, is_dst=None)
unix_time = (timezone_aware_datetime - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()
return unix_time
dt = datetime(year=2017, month=1, day=17, hour=12, minute=0, second=0)
print timezoned_unixtime(latitude=40.747854, longitude=-74.004733, dt=dt)
其他回答
通过使用纬度和经度得到当前位置下面的时区代码为我工作
String data = null;
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Location ll = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
double lat = 0,lng = 0;
if(ll!=null){
lat=ll.getLatitude();
lng=ll.getLongitude();
}
System.out.println(" Last known location of device == "+lat+" "+lng);
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
timezoneurl = timezoneurl+"location=22.7260783,75.8781553×tamp=1331161200";
// timezoneurl = timezoneurl+"location="+lat+","+lng+"×tamp=1331161200";
URL url = new URL(timezoneurl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
try {
iStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
urlConnection.disconnect();
}
try {
if(data!=null){
JSONObject jobj=new JSONObject(data);
timezoneId = jobj.getString("timeZoneId");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
format.setTimeZone(TimeZone.getTimeZone(timezoneId));
Calendar cl = Calendar.getInstance(TimeZone.getTimeZone(timezoneId));
System.out.println("time zone id in android == "+timezoneId);
System.out.println("time zone of device in android == "+TimeZone.getTimeZone(timezoneId));
System.out.println("time fo device in android "+cl.getTime());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It's indeed important to recognize that this a more complicated problem than most would suspect. In practice many of us are also willing to accept a working set of code that works for "as many cases as possible", where at least its fatal issues can be identified and minimized collectively. So I post this with all of that and the spirit of the OP in mind. Finally, for practical value to others who are trying to convert GPS to timezone with the end goal of having a location-sensitive time object (and more importantly to help advance the quality of average implementations with time objects that follow from this wiki) here is what I generated in Python (please feel free to edit):
import pytz
from datetime import datetime
from tzwhere import tzwhere
def timezoned_unixtime(latitude, longitude, dt):
tzw = tzwhere.tzwhere()
timezone_str = tzw.tzNameAt(latitude, longitude)
timezone = pytz.timezone(timezone_str)
timezone_aware_datetime = timezone.localize(dt, is_dst=None)
unix_time = (timezone_aware_datetime - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()
return unix_time
dt = datetime(year=2017, month=1, day=17, hour=12, minute=0, second=0)
print timezoned_unixtime(latitude=40.747854, longitude=-74.004733, dt=dt)
There are several sources online that have geojson data for timezones (here's one, here's another) Use a geometry library to create polygon objects from the geojson coordinates (shapely [python], GEOS [c++], JTS [java], NTS [.net]). Convert your lat/lng to a point object (however your library represents that) and check if it intersects the timezone polygon. from shapely.geometry import Polygon, Point def get_tz_from_lat_lng(lat, lng): for tz, geojson in timezones.iteritems(): coordinates = geojson['features'][0]['geometry']['coordinates'] polygon = Polygon(coordinates) point = Point(lng, lat) if polygon.contains(point): return tz
对于我们这些使用Javascript并希望通过谷歌api从邮政编码获取时区的人来说,这里有一个方法。
通过地理定位获取lat/lng 通过这个参数获取时区 进入时区API。 此处使用Luxon进行时区转换。
注意:我的理解是,邮政编码在不同的国家并不是唯一的,所以这可能最适合在美国使用。
const googleMapsClient; // instantiate your client here
const zipcode = '90210'
const myDateThatNeedsTZAdjustment; // define your date that needs adjusting
// fetch lat/lng from google api by zipcode
const geocodeResponse = await googleMapsClient.geocode({ address: zipcode }).asPromise();
if (geocodeResponse.json.status === 'OK') {
lat = geocodeResponse.json.results[0].geometry.location.lat;
lng = geocodeResponse.json.results[0].geometry.location.lng;
} else {
console.log('Geocode was not successful for the following reason: ' + status);
}
// prepare lat/lng and timestamp of profile created_at to fetch time zone
const location = `${lat},${lng}`;
const timestamp = new Date().valueOf() / 1000;
const timezoneResponse = await googleMapsClient
.timezone({ location: location, timestamp: timestamp })
.asPromise();
const timeZoneId = timezoneResponse.json.timeZoneId;
// adjust by setting timezone
const timezoneAdjustedDate = DateTime.fromJSDate(
myDateThatNeedsTZAdjustment
).setZone(timeZoneId);
https://en.wikipedia.org/wiki/Great-circle_distance
下面是一个使用JSON数据的很好的实现: https://github.com/agap/llttz
public TimeZone nearestTimeZone(Location node) {
double bestDistance = Double.MAX_VALUE;
Location bestGuess = timeZones.get(0);
for (Location current : timeZones.subList(1, timeZones.size())) {
double newDistance = distanceInKilometers(node, current);
if (newDistance < bestDistance) {
bestDistance = newDistance;
bestGuess = current;
}
}
return java.util.TimeZone.getTimeZone(bestGuess.getZone());
}
protected double distanceInKilometers(final double latFrom, final double lonFrom, final double latTo, final double lonTo) {
final double meridianLength = 111.1;
return meridianLength * centralAngle(latFrom, lonFrom, latTo, lonTo);
}
protected double centralAngle(final Location from, final Location to) {
return centralAngle(from.getLatitude(), from.getLongitude(), to.getLatitude(), to.getLongitude());
}
protected double centralAngle(final double latFrom, final double lonFrom, final double latTo, final double lonTo) {
final double latFromRad = toRadians(latFrom),
lonFromRad = toRadians(lonFrom),
latToRad = toRadians(latTo),
lonToRad = toRadians(lonTo);
final double centralAngle = toDegrees(acos(sin(latFromRad) * sin(latToRad) + cos(latFromRad) * cos(latToRad) * cos(lonToRad - lonFromRad)));
return centralAngle <= 180.0 ? centralAngle : (360.0 - centralAngle);
}
protected double distanceInKilometers(final Location from, final Location to) {
return distanceInKilometers(from.getLatitude(), from.getLongitude(), to.getLatitude(), to.getLongitude());
}
}