更改Javascript的getTimezoneOffset以返回不同的时区偏移量?

zhk*_*yth 3 javascript

有没有办法更改Javascript的getTimezoneOffset以返回不同的时区偏移量?

Fox的例子,我当地的时区是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
Run Code Online (Sandbox Code Playgroud)

那么,如何让它显示GMT-1?

参考链接:

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

Mat*_*att 7

我不认为javascript有直接的方法来做到这一点,所以你可以自己计算或使用日期库.

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

}
Run Code Online (Sandbox Code Playgroud)

然后将偏移量传递给+1或-5等,如同 calcTime('-1')


tfo*_*ont 5

使用纯 JavaScript 快速解决方案。

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

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

alert(utc);
Run Code Online (Sandbox Code Playgroud)