How to get a time zone from a location using latitude and longitude coordinates?

后端 未结 17 1566
走了就别回头了
走了就别回头了 2020-11-21 04:38

Given the latitude and longitude of a location, how does one know what time zone is in effect in that location?

In most cases, we are looking for an IANA/Olson time z

17条回答
  •  清歌不尽
    2020-11-21 04:57

    For those of us using Javascript and looking to get a timezone from a zip code via Google APIs, here is one method.

    1. Fetch the lat/lng via geolocation
    2. fetch the timezone by pass that into the timezone API.
      • Using Luxon here for timezone conversion.

    Note: my understanding is that zipcodes are not unique across countries, so this is likely best suited for use in the USA.

    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);
    

提交回复
热议问题