2011-12-22 75 views
3

有沒有辦法改變Javascript的getTimezoneOffset返回不同的時區偏移?更改Javascript的getTimezoneOffset以返回不同的時區偏移量?

福克斯例如,我的本地時區是GMT-8,但我想Date.getTimezoneOffset()返回GMT-1,所以我這樣做如下:

var timeZone1 = new Date(Date.parse("2011-01-01T00:00:00-01:00")); 
document.write("The local time zone is: GMT " + timeZone1.getTimezoneOffset()/60); 
//show:The local time zone is: GMT-8 

因此,如何使它顯示GMT-1?

REFFERENCE鏈接:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset

回答

6

我不認爲JavaScript有一個直接的方式做到這一點,SOOOO你可以自己進行計算或使用最新的圖書館。

http://code.google.com/p/datejs/ datejs是一個不錯的圖書館。

要計算自己嘗試,

function calcTime(offset) { 
    d = new Date(); 

    //Deal with dates in milliseconds for most accuracy 
    utc = d.getTime() + (d.getTimezoneOffset() * 60000); 
    newDateWithOffset = new Date(utc + (3600000*offset)); 

    //This will return the date with the locale format (string), or just return newDateWithOffset 
    //and go from there. 
    return newDateWithOffset.toLocaleString(); 

} 

然後通過偏移像+1或-5,等等。在calcTime('-1')

+0

感謝Matt.That真的幫助我=)除此之外,我仍然困惑的是,當我創建一個字符串「2011-01-01T00一個Date對象:00:00 -01:00「,我會認爲js創建了一個Date對象,並且它的時區已經設置爲東1.所以當我使用getTimezoneOffset()時,它應該讓我回到指定的值,但不是我的本地時區。只覺得奇怪... – zhkzyth 2011-12-23 12:54:46

+0

我建議使用時區插件的moment.js。 – Gordolio 2014-03-06 23:37:33

-1

getTimezoneOffset()函數總是返回時區機器的偏移量。

3

使用純JavaScript的快速而快速的解決方案。

var currentTime = new Date(); 
 
var currentTimezone = currentTime.getTimezoneOffset(); 
 
    currentTimezone = (currentTimezone/60) * -1; 
 

 
if (currentTimezone !== 0) 
 
{ 
 
    utc = currentTimezone > 0 ? ' +' : ' '; 
 
    utc += currentTimezone 
 
} 
 

 
alert(utc);

相關問題