首页 > 怎么把ajax头文件请求来的时间强制转换为北京时间

怎么把ajax头文件请求来的时间强制转换为北京时间

我用ajax的头文件请求了一个乔治格林时间,但是如果用new Date用户的机子的时区不对就不能转换为正确的时间。我想强制+8个小时转为北京时间,有什么方法吗?


如果不能修改后端程序的话那就只好在前端自行转换一下了,不过也不是非常推荐强制转换成 GMT+8 就是了,新疆地区以及各种非 +8 地区表示鸭梨很大的说。直接使用 getTimezoneOffset 可以获得时差数,然后加进去就好了。

function getHTML( url ) {
    return new Promise(function(resolve, reject) {
        var xhr = new XMLHttpRequest;
        xhr.open("HEAD", url, true);
        xhr.responseType = "document";
        xhr.onload = function() {
            if( xhr.status === 200 ) {
                resolve( xhr );
            } else reject( Error( xhr.status ) );
        }
        xhr.onerror = function() {
            reject( Error( xhr.status ) );
        }
        xhr.send( null );
    })
}
getHTML( location.href ).then( function( xhr ) {
    var time = xhr.getResponseHeader("Date");
    time = new Date( time );
    time = time.getTime() - (new Date).getTimezoneOffset() * 60000;
    time = new Date( time );
    console.log( time );
} );

最后友情提醒一下,如果后端是 PHP 的话因为 PHP 的时间单位是秒而 JS 是毫秒需要 * 1000的。


javascriptyourDate.setHours(yourDate.getHours() + 8);

不知道有没有理解错你意思

【热门文章】
【热门文章】