Search code examples
javascriptgoogle-mapsdatetimegoogle-apigoogle-maps-timezone

Javascript - Calculate time from the rawOffset Google timezone API


I am developing an application to get the local time of city. I am using google Geocode API to get the latitude and longitude of a city and the same is passed to the timezone API.

Time Zone API return the following

{
"dstOffset" : 0,
"rawOffset" : 0,
"status" : "OK",
"timeZoneId" : "Europe/London",
"timeZoneName" : "Greenwich Mean Time"
}

I need to calculate the time for the following. From this SO answer, I got the following code to get the local time from rawOffset.

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

alert("The local time is " + nd.toLocaleString());
}
calcTime(-28800.0);

But this is having one hour delay in time for cities like London, Washington, NewYork and returns correct time for Arizona.

Also. I am not aware of this relation between local time and rawOffset parameter to calculate the time. Please explain what this rawOffset parameter is and how to fix this one hour time delay for some cities.

In Google TimeZone API Documentation, I read that

The local time of a given location is the sum of the timestamp parameter, and the dstOffset and rawOffset fields from the result.

What is the timestamp parameter here? I couldn't give anything other than 1331161200.

Any help is greatly appreciated. Thanks in advance.

UPDATE

FIX : This is because I am passing timestamp parameter as 1331161200 in the timezone API. When I replaced timestamp with the following code, I am getting correct response from the Google APIs with dstOffset and rawOffset.

myDate = new Date('1/1/1970');
timeStamp = myDate.getTime();

Can anyone give me the technical explanation of how it worked?


Solution

  • You haven't considered the Daylight Savings Time offset, which is why certain cities are off by an hour.

    calcTime(rawOffset+dstOffset);
    

    Timestamp contains both the date and time for as DST is only occurs in certain periods of the year. https://stackoverflow.com/a/10428184/3583980