Javascript日期在ie8中显示为nan

Javascript date shows nan in ie8

下面的代码在除 IE8 之外的任何浏览器中都能正常运行。我正在从服务器上获取时间并尝试在 IE8 中显示日期字符串和服务器时间。我得到的是字符串 serverHour 是未定义的 undefined undefined undefined,而对于时间 testHours,我得到的是 nan。我尝试使用 moment.js 来获取要显示的日期,但我得到了相同的结果。任何指导将不胜感激。我已尝试以几种不同的方式重新格式化日期字符串,但我无法找到有效的组合。我一定是遗漏了一些非常基本的东西。

var xmlHttp;
var offset = 0;
var today = new Date();

/* 
return the standard time timezone offset regardless of whether the current time is on standard or daylight saving time. 
http://www.webdeveloper.com/forum/showthread.php?228309-Getting-server-date-time-with-no-server-side-script
*/
Date.prototype.stdTimezoneOffset = function () {
    var jan = new Date(this.getFullYear(), 0, 1);
    var jul = new Date(this.getFullYear(), 6, 1);
    return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}

/*
Determine if the current time is on daylight saving time or not. We simply compare the current  timezone offset with the standard one. 
If they are equal then the current time is standard time. If they are not     then the current   time is daylight saving time. This second 
method will return true when the current time is daylight saving time and false when it is    standard time.
http://www.webdeveloper.com/forum/showthread.php?228309-Getting-server-date-time-with-no-server-       side-script
*/
Date.prototype.dst = function () {
    return this.getTimezoneOffset() < this.stdTimezoneOffset();
}

// Convert GMT server time to Pacific time and return date.
function getServerTime(serverDateMs,offset) {
    var date = new Date(serverDateMs + offset * 3600 * 1000);
    return date;
}

// Function to get server time in GMT
function srvTime() {

// Create an XML object to collect information from server
try {
    //FF, Opera, Safari, Chrome
    xmlHttp = new XMLHttpRequest();
}
catch (err1) {
    //IE
    try {
        xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
    }
    catch (err2) {
        try {
            xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
        }
        catch (err3) {
            //AJAX not supported, use CPU time.
            alert("AJAX not supported");
        }
    }
}

// Request information from the server using XML object
xmlHttp.open('POST', window.location.href, false);
xmlHttp.send();
return xmlHttp.getResponseHeader("Date");
}
// Set offset if daylight savings time or standard time
if (today.dst() == true) { offset = -7; }
else { offset = -8; }

var x = srvTime();

//i have: Fri, 02 Jan 2015 22:54:05 GMT
// modify the string to remove comma and GMT
var dateString = x.replace(",", "").replace("GMT", "");

var a = dateString.split(" ");

//I want: Nov 06 2012 23:29:33 +0000
// reorganize to match above format
var newDatString = a[2] + " " + a[1] + " " + a[3] + " " + a[4];

// create the date object
var serverT = new Date(newDatString);
// get date/time in milliseconds
var serverDateMs = serverT.getTime();
// convert GMT time to pacific time
var serverDatePacific = getServerTime(serverDateMs, offset);
// create date object from pacific time
var serverHour = new Date(serverDatePacific);
// get hours from pacific time date object
var testHour = serverHour.getHours();

很难测试您的代码,因为您没有说明哪个变量进入 "output"(输出将是代码中显示 NaN 的位置)

但是对变量进行了测试,发现问题出在您的 XMLHttpRequest

XMLHttpRequest 和 'POST' return header 像这样(没有数据 header):

Keep-Alive: timeout=5, max=100
Content-Type: text/html
Content-Length: 3119
Last-Modified: Sun, 04 Jan 2015 03:38:27 GMT

但是使用HEAD方法,return像这样:

Date: Sun, 04 Jan 2015 03:41:30 GMT
Server: Apache/2.4.3 (Win64)
Last-Modified: Sun, 04 Jan 2015 03:41:28 GMT
Accept-Ranges: bytes
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive
Content-Type: text/html

但这不是解决方案,因为 HEAD 不阻止缓存并且 "sync-mode" 是 "bad"。

如果我理解你的代码,你想在没有像 Python、PHP、Ruby 或其他解释器语言的情况下获得服务器时间,最好的方法是使用 Ajax(异步)。

Synchronous XMLHttpRequest outside of workers is in the process of being removed from the web platform as it has detrimental effects to the end user's experience. (This is a long process that takes many years.) Developers must not pass false for the async argument when the JavaScript global environment is a document environment. User agents are strongly encouraged to warn about such usage in developer tools and may experiment with throwing an InvalidAccessError exception when it occurs. Read: http://xhr.spec.whatwg.org/

使用 "async mode",像这样:

xmlHttp.open('HEAD', URL, true);//true = async
xmlHttp.onreadystatechange = function () { ... };

The HEAD method 与 GET 相同,只是服务器不得 return 在响应中使用 message-body。响应 HEAD 请求的 HTTP headers 中包含的元信息应该与响应 GET 请求发送的信息相同。此方法可用于获取有关请求隐含的实体的元信息,而无需传输 entity-body 本身。此方法通常用于测试超文本链接的有效性、可访问性和最近的修改。

因此您可以创建一个使用回调获取日期的函数,并使用 new Date().getTime() 防止缓存:

function getDateFromServer(done, fail) {
    var xmlHttp, uri, dateHeader;

    if (window.XMLHttpRequest) {
        xmlHttp = new window.XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            xmlHttp = new window.ActiveXObject("Msxml2.XMLHTTP");
        } catch (ee1) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (ee2) {
                fail(-1, ee2.message);
                return;
            }
        }
    } else {
        fail(-1, "Your browser don't support XMLHttpRequest");
        return;
    }

    uri  = String(window.location);//Get same origin
    uri += uri.indexOf("?") !== -1 ? "&_=" : "?_=";
    uri += new Date().getTime();//Prevent cache

    xmlHttp.open("HEAD", uri, true);
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState === 4) {
            dateHeader = xmlHttp.getResponseHeader("Date");
            if (dateHeader) {
                done(dateHeader);
            } else {
                fail(xmlHttp.status, "Date header is undefined");
            }
        }
    };
    xmlHttp.send(null);
}

此函数有两个参数,第一个参数在 ajax header return 日期运行,第二个参数在您连接到服务器或 ISP 时出错。

使用代码(注意这是异步的,需要回调):

getDateFromServer(function (x) {//First argument is "done" callback
    alert(x);
    //put your code
}, function(status, msg) {//Second argument is "fail" callback
    alert("Error in request, error: " + status + " / " + msg);
});

jsfiddle 中的示例:http://jsfiddle.net/9cy9kvsk/