Search code examples
google-mapsgoogle-maps-api-3utclocaltime

How to calculate the utc time and the local time from google map?


How can I calculate the utc time and the local time from google map?

For instance, this is the json result from google,

{
   "dstOffset" : 0.0,
   "rawOffset" : -28800.0,
   "status" : "OK",
   "timeZoneId" : "America/Los_Angeles",
   "timeZoneName" : "Pacific Standard Time"
}

My function,

   function calcTime(offset) {
        var d = new Date();
        var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
        var nd = new Date(utc + (1000*offset));

        return nd.toLocaleString();
    }

Usage,

// Calculate the time.
var local = calcTime(-28800.0);
var utc = calcTime(0.0);

Am I correct?


Solution

  • You can always use the Timezone API offered by Google to calculate the local time. While requesting the data from this API you have to make a GET request to the following API.

    https://maps.googleapis.com/maps/api/timezone/outputFormat?parameters
    

    EDIT

    In the parameters the required values are the coordinates of the location in lat/lng and the timestamp. The timestamp is always the UTC time which you can get by going on this link. You can directly put that in the timestamp variable as UTC and get the response.

    To calculate the local time you have to calculate the sum of the timestamp parameter, and the dstOffset and rawOffset fields from the result. The dstOffset and the rawOffset fields are the JSON responses obtained after you send a request.