谷歌时区

Google Timezone

本文关键字:时区 谷歌      更新时间:2023-09-26

我对使用谷歌时区有点困惑,虽然这工作得很好,但我无法获得正确的时间。

这是我的代码:

var xhr;
if (window.XMLHttpRequest) {
  xhr = new XMLHttpRequest();
} else {
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var timeStamp = Math.floor(new Date().getTime() / 1000);
var url = "https://maps.googleapis.com/maps/api/timezone/json?location=41.010734,9.0039&timestamp=" + timeStamp ;
xhr.open("GET", url, false);
xhr.send(null);
var resp = JSON.parse(xhr.responseText);
var time = new Date((resp.dstOffset + resp.rawOffset + timeStamp) * 1000);
var span = " AM";
var hours = time.getUTCHours();
if (hours > 12) {
  span = " PM";
  hours -= 12;
}
CurrentTime = ((hours + '').length == 1 ? '0' + hours : hours) + ":" + ((time.getUTCMinutes() + '').length == 1 ? '0' + time.getUTCMinutes() : time.getUTCMinutes()) + span;
console.log("Time is: " + CurrentTime);

我正在使用并返回数据,然而,因为我正在从英国传递时间并检索法国的一个位置,所以时间减少了1小时。我知道这与DST和返回数据的原始值有关,但无法确定如何确保这始终是正确的。

要获取utc时间戳,可以使用:

var now = new Date;
var utc_timestamp = Date.UTC(
    now.getUTCFullYear(),
    now.getUTCMonth(), 
    now.getUTCDate() ,          
    now.getUTCHours(), 
    now.getUTCMinutes(), 
    now.getUTCSeconds(), 
    now.getUTCMilliseconds()
);

更新小提琴:

var xhr;
if (window.XMLHttpRequest) {
  xhr = new XMLHttpRequest();
} else {
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var now = new Date;
var utc_timestamp = Date.UTC(
    now.getUTCFullYear(),
    now.getUTCMonth(), 
    now.getUTCDate() ,          
    now.getUTCHours(), 
    now.getUTCMinutes(), 
    now.getUTCSeconds(), 
    now.getUTCMilliseconds()
);
var timeStamp = Math.floor(utc_timestamp / 1000);
var url = "https://maps.googleapis.com/maps/api/timezone/json?location=41.010734,9.0039&timestamp=" + timeStamp ;
xhr.open("GET", url, false);
xhr.send(null);
var resp = JSON.parse(xhr.responseText);
var time = new Date((resp.dstOffset + resp.rawOffset + timeStamp) * 1000);
var span = " AM";
var hours = time.getUTCHours();
if (hours > 12) {
  span = " PM";
  hours -= 12;
}
CurrentTime = ((hours + '').length == 1 ? '0' + hours : hours) + ":" + ((time.getUTCMinutes() + '').length == 1 ? '0' + time.getUTCMinutes() : time.getUTCMinutes()) + span;
console.log("Time is: " + CurrentTime);