2016-09-06 10 views
0

Googleタイムゾーンを使用して少し困惑していますが、これはうまくいきますが、正しい時間を取得できません。Google Timezone

これは私のコードです:

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値とRaw値とは関係がありますが、これが正しいことを確認する方法を理解することはできません。 私を助けてください。

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

更新フィドル:

+0

タイムスタンプをしているあなたはします追加はローカルではなく、utcである必要があると私は考えています。オフセットはutcに関連しているからです。しかし、それはあなたが得ているようです。パズルリング。 –

+0

https://developers.google.com/maps/documentation/timezone/introに基づいて、緯度または経度を引用符で囲む必要はないようです。私はそれが問題だとは想像できません。 –

+0

いいえ、返される時間が1時間遅れるという問題はありません – user1824963

答えて

0

UTCタイムスタンプを取得するには、使用することができ、GoogleのAPIに渡さ

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