Javascript date 在 ie8 中显示 nan

Javascript date shows nan in ie8

本文关键字:显示 nan ie8 date Javascript      更新时间:2023-09-26

下面的代码在IE8以外的任何浏览器中都能很好地工作。我正在从服务器中获取时间并尝试在IE8中显示日期字符串和服务器小时。我得到的是字符串,serverHour,是未定义的未定义未定义未定义,对于小时,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();
很难

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

但是对变量进行了测试,并意识到问题出在您的XMLHttpRequest上。

XMLHttpRequest带有"POST"返回标头,如下所示(不带数据标头):

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

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

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 不会阻止缓存,并且"同步模式"是"坏的"。

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

工作人员外部的同步XMLHttpRequest正在从 Web 平台中删除,因为它对最终用户的体验有不利影响。(这是一个漫长的过程,需要很多年。当 JavaScript 全局环境是文档环境时,开发人员不得为 async 参数传递 false。强烈建议用户代理在开发人员工具中警告此类用法,并且可以尝试在发生 InvalidAccessError 异常时引发该异常。阅读:http://xhr.spec.whatwg.org/

使用"异步模式",如下所示:

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

HEAD 方法与 GET 相同,只是服务器不得在响应中返回消息正文。响应 HEAD 请求的 HTTP 标头中包含的元信息应与响应 GET 请求时发送的信息相同。此方法可用于获取有关请求所隐含的实体的元信息,而无需传输实体主体本身。此方法通常用于测试超文本链接的有效性、可访问性和最近修改。

因此,您可以使用回调来创建一个函数来获取日期,并使用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 标头返回日期时运行,第二个参数在连接到服务器或 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/