gpt4 book ai didi

Javascript 日期在 ie8 中显示 nan

转载 作者:行者123 更新时间:2023-12-02 20:25:46 27 4
gpt4 key购买 nike

下面的代码可以在除 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”返回 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 方法,返回如下:

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(异步)。

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/

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

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

The HEAD method与 GET 相同,只是服务器不得在响应中返回消息正文。响应 HEAD 请求的 HTTP header 中包含的元信息应该与响应 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 header 返回日期时运行,第二个参数在连接到服务器或 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/

关于Javascript 日期在 ie8 中显示 nan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27749999/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com